package xyz.wbsite;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.event.ApplicationContextInitializedEvent;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import xyz.wbsite.frame.base.LocalData;

@SpringBootApplication
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.addListeners(getListener());
        application.run(args);
    }

    /**
     * 用于启动时获取上下文，因为在启动过程中通过工具LocalData.getContext()获取为null
     * 所以为了兼容这种需求，通过此监听可以在SpringApplication未启动完成时获得上下文
     *
     * @return ApplicationListener
     */
    private static ApplicationListener getListener() {
        return new ApplicationListener<ApplicationEvent>() {
            @Override
            public void onApplicationEvent(ApplicationEvent applicationEvent) {
                if (applicationEvent instanceof ApplicationContextInitializedEvent) {
                    LocalData.setContext(((ApplicationContextInitializedEvent) applicationEvent).getApplicationContext());
                }
            }
        };
    }
}