简述
SpringApplication
的生命周期事件一共有七个,它们发生的顺序如下:
ApplicationStartingEvent
ApplicationEnvironmentPreparedEvent
ApplicationContextInitializedEvent
ApplicationPreparedEvent
ApplicationStartedEvent
ApplicationReadyEvent
ApplicationFailedEvent
2、具体讲解
2.1 APPLICATIONSTARTINGEVENT
这个事件是在一个SpringApplication
对象的初始化和监听器的注册之后,抛出的。
2.2 APPLICATIONENVIRONMENTPREPAREDEVENT
这个事件在Environment
对象创建之后,Context
对象创建之前,抛出。
2.3 APPLICATIONCONTEXTINITIALIZEDEVENT
这个事件在ApplicationContext
对象被初始化后抛出,抛出的时候,所有bean
的定义还没被加载。
2.4 APPLICATIONPREPAREDEVENT
这个事件在bean
定义被加载之后,Context
对象刷新之前抛出。
2.5 APPLICATIONSTARTEDEVENT
这个事件在Context
对象刷新之后,应用启动器被调用之前抛出。
2.6 APPLICATIONREADYEVENT
这个事件在应用启动器被调用之后抛出,这个代表着应用已经被正常的启动,可以接收请求了。
2.7 APPLICATIONFAILEDEVENT
这个事件只有在应用启动出现异常,无法正常启动时才会抛出。
3、编写代码,验证结论
3.1 编写事件监听器
我在这里只写一个,其他六个的类似:
public class ApplicationContextInitializedEventListener implements ApplicationListener<ApplicationContextInitializedEvent> {
@Override
public void onApplicationEvent(ApplicationContextInitializedEvent applicationContextInitializedEvent) {
System.out.println("ApplicationContextInitializedEvent");
}
}
3.2 添加监听器
启动类如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.test.listener.*;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication a = new SpringApplication(App.class);
//添加监听器
a.addListeners(new ApplicationContextInitializedEventListener(), new ApplicationEnvironmentPreparedEventListener(),
new ApplicationFailedEventListener(), new ApplicationPreparedEventListener(), new ApplicationReadyEventListener(),
new ApplicationStartedEventListener(), new ApplicationStartingEventListener());
a.run(args);
}
}