測試代碼:
package com.github.abel533.event; import com.github.abel533.C; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * @author liuzh */ @Component public class ApplicationListenerImpl implements ApplicationListener<ApplicationEvent> { public ApplicationListenerImpl() { C.print("ApplicationListenerImpl#constructor"); } @Override public void onApplicationEvent(ApplicationEvent event) { C.print("ApplicationListener#" + event.getClass().getSimpleName()); } }
package com.github.abel533.event; import com.github.abel533.lifecycle.BeanLifecycle; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ListenerApplication { public static void main(String[] args) { SpringApplication.run(ListenerApplication.class, args).close(); } }
用以上代碼實現 ApplicationListener 接口,輸出所有事件。
當以 @Component 方式配置時
事件觸發順序如下:
ApplicationListener#ContextRefreshedEvent
ApplicationListener#ServletWebServerInitializedEvent
ApplicationListener#ApplicationStartedEvent
ApplicationListener#ApplicationReadyEvent
ApplicationListener#ContextClosedEvent
當通過 /META-INF/spring.factories 配置時
配置內容如下:
org.springframework.context.ApplicationListener=com.github.abel533.event.ApplicationListenerImpl
此時輸出的事件順序如下:
差異
很容易通過對比發現,Event 觸發的時間極早,以至於 @Component 方式只能從第 4 個事件才開始獲取到。
從這兩種方式的加載時機來看這個差異產生的原因。
在 SpringApplication 構造方法中,就調用 getSpringFactoriesInstances 來獲取 /META-INF/spring.factories 配置的 ApplicationListener,代碼如下:
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); this.webApplicationType = WebApplicationType.deduceFromClasspath(); setInitializers((Collection) getSpringFactoriesInstances( ApplicationContextInitializer.class)); setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); this.mainApplicationClass = deduceMainApplicationClass(); }
在 SpringFactoriesLoader#loadFactoryNames 實現了從該配置文件獲取實現名的方法。從這之后就能收到后續觸發的事件。
通過 @Component 方式時,在 SpringApplication#refresh 中調用 registerListeners 獲取的所有 ApplicationListener 接口的實現。代碼如下:
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { try { // 注冊所有 ApplicationListener 實現 registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // 這里會觸發 ContextRefreshedEvent finishRefresh(); } } }
下面先分析前 4 個無法獲取的事件順序。
ApplicationStartingEvent
第 0 個事件是在 EventPublishingRunListener#starting 中發布的,代碼如下:
@Override public void starting() { this.initialMulticaster.multicastEvent( new ApplicationStartingEvent(this.application, this.args)); }
此時的堆棧調用情況如下:
onApplicationEvent:15, ApplicationListenerImpl (com.github.abel533.event) doInvokeListener:172, SimpleApplicationEventMulticaster (org.springframework.context.event) invokeListener:165, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:139, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:127, SimpleApplicationEventMulticaster (org.springframework.context.event) starting:69, EventPublishingRunListener (org.springframework.boot.context.event) starting:48, SpringApplicationRunListeners (org.springframework.boot) run:302, SpringApplication (org.springframework.boot) run:1260, SpringApplication (org.springframework.boot) run:1248, SpringApplication (org.springframework.boot) main:12, ListenerApplication (com.github.abel533.event)
ApplicationEnvironmentPreparedEvent
第 1 個事件是在 EventPublishingRunListener#environmentPrepared 中發布的,代碼如下:
@Override public void environmentPrepared(ConfigurableEnvironment environment) { this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent( this.application, this.args, environment)); }
此時的堆棧調用情況如下:
onApplicationEvent:15, ApplicationListenerImpl (com.github.abel533.event) doInvokeListener:172, SimpleApplicationEventMulticaster (org.springframework.context.event) invokeListener:165, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:139, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:127, SimpleApplicationEventMulticaster (org.springframework.context.event) environmentPrepared:75, EventPublishingRunListener (org.springframework.boot.context.event) environmentPrepared:54, SpringApplicationRunListeners (org.springframework.boot) prepareEnvironment:347, SpringApplication (org.springframework.boot) run:306, SpringApplication (org.springframework.boot) run:1260, SpringApplication (org.springframework.boot) run:1248, SpringApplication (org.springframework.boot) main:12, ListenerApplication (com.github.abel533.event)
ApplicationContextInitializedEvent
第 2 個事件是在 EventPublishingRunListener#contextPrepared 中發布的,代碼如下:
@Override public void contextPrepared(ConfigurableApplicationContext context) { this.initialMulticaster.multicastEvent(new ApplicationContextInitializedEvent( this.application, this.args, context)); }
此時的堆棧調用情況如下:
onApplicationEvent:15, ApplicationListenerImpl (com.github.abel533.event) doInvokeListener:172, SimpleApplicationEventMulticaster (org.springframework.context.event) invokeListener:165, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:139, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:127, SimpleApplicationEventMulticaster (org.springframework.context.event) contextPrepared:81, EventPublishingRunListener (org.springframework.boot.context.event) contextPrepared:60, SpringApplicationRunListeners (org.springframework.boot) prepareContext:374, SpringApplication (org.springframework.boot) run:314, SpringApplication (org.springframework.boot) run:1260, SpringApplication (org.springframework.boot) run:1248, SpringApplication (org.springframework.boot) main:12, ListenerApplication (com.github.abel533.event)
ApplicationPreparedEvent
第 3 個事件是在 EventPublishingRunListener#contextLoaded 中發布的,代碼如下:
@Override public void contextLoaded(ConfigurableApplicationContext context) { for (ApplicationListener<?> listener : this.application.getListeners()) { if (listener instanceof ApplicationContextAware) { ((ApplicationContextAware) listener).setApplicationContext(context); } context.addApplicationListener(listener); } this.initialMulticaster.multicastEvent( new ApplicationPreparedEvent(this.application, this.args, context)); }
此時的堆棧調用情況如下:
onApplicationEvent:15, ApplicationListenerImpl (com.github.abel533.event) doInvokeListener:172, SimpleApplicationEventMulticaster (org.springframework.context.event) invokeListener:165, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:139, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:127, SimpleApplicationEventMulticaster (org.springframework.context.event) contextLoaded:93, EventPublishingRunListener (org.springframework.boot.context.event) contextLoaded:66, SpringApplicationRunListeners (org.springframework.boot) prepareContext:393, SpringApplication (org.springframework.boot) run:314, SpringApplication (org.springframework.boot) run:1260, SpringApplication (org.springframework.boot) run:1248, SpringApplication (org.springframework.boot) main:12, ListenerApplication (com.github.abel533.event)
ContextRefreshedEvent
在上面差異中提到 finishRefresh 會觸發 ContextRefreshedEvent,代碼如下:
@Override protected void finishRefresh() { super.finishRefresh(); WebServer webServer = startWebServer(); if (webServer != null) { publishEvent(new ServletWebServerInitializedEvent(webServer, this)); } }
注意 super.finishRefresh,代碼如下(有刪減):
protected void finishRefresh() { // Publish the final event. publishEvent(new ContextRefreshedEvent(this)); }
ServletWebServerInitializedEvent
注意前面 finishRefresh 方法,如果存在 webServer != null,就會發布 ServletWebServerInitializedEvent。
ApplicationStartedEvent
在 SpringApplication#run 方法中,執行完成后,就會調用 listeners.started(context); 方法,在這里面會發布 ApplicationStartedEvent。
ApplicationReadyEvent
和上面 ApplicationStartedEvent 一樣,如下代碼(有刪減):
// ApplicationStartedEvent listeners.started(context); callRunners(context, applicationArguments); // ApplicationReadyEvent listeners.running(context);
執行完所有 ApplicationRunner 和 CommandLineRunner 接口方法后,就會調用 listeners.running(context),在這里面就會發布 ApplicationReadyEvent。
在這之后就沒有運行期的主要事件了(不考慮 devtools 重啟)。在這個事件里,可以請求zookeeper進行服務注冊,以便其它服務發現並調用它等相關操作。
ContextClosedEvent
當調用關閉方法的時候,自然就觸發了 ContextClosedEvent,調用堆棧如下:
onApplicationEvent:20, ApplicationListenerImpl (com.github.abel533.event) doInvokeListener:172, SimpleApplicationEventMulticaster (org.springframework.context.event) invokeListener:165, SimpleApplicationEventMulticaster (org.springframework.context.event) multicastEvent:139, SimpleApplicationEventMulticaster (org.springframework.context.event) publishEvent:398, AbstractApplicationContext (org.springframework.context.support) publishEvent:355, AbstractApplicationContext (org.springframework.context.support) doClose:994, AbstractApplicationContext (org.springframework.context.support) close:961, AbstractApplicationContext (org.springframework.context.support) main:12, ListenerApplication (com.github.abel533.event)
本文轉自:https://blog.csdn.net/isea533/article/details/100146833