Spring 執行順序:Event 事件

回目錄

代碼:https://gitee.com/free/boot-order/tree/master/src/main/java/com/github/abel533/event

實現 ApplicationListener 接口,輸出所有事件。

當以 @Component 方式配置時

事件觸發順序如下:

  1. ApplicationListener#ContextRefreshedEvent
  2. ApplicationListener#ServletWebServerInitializedEvent
  3. ApplicationListener#ApplicationStartedEvent
  4. ApplicationListener#ApplicationReadyEvent
  5. ApplicationListener#ContextClosedEvent

當通過 /META-INF/spring.factories 配置時

配置內容如下:

org.springframework.context.ApplicationListener=com.github.abel533.event.ApplicationListenerImpl

此時輸出的事件順序如下:

  1. ApplicationListener#ApplicationStartingEvent
  2. ApplicationListener#ApplicationEnvironmentPreparedEvent
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.1.1.RELEASE)
    
  3. ApplicationListener#ApplicationContextInitializedEvent
  4. ApplicationListener#ApplicationPreparedEvent
  5. ApplicationListener#ContextRefreshedEvent 這裏
  6. ApplicationListener#ServletWebServerInitializedEvent
  7. ApplicationListener#ApplicationStartedEvent
  8. ApplicationListener#ApplicationReadyEvent
  9. ApplicationListener#ContextClosedEvent

差異

很容易通過對比發現,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);

執行完所有 ApplicationRunnerCommandLineRunner 接口方法後,就會調用 listeners.running(context),在這裏面就會發布 ApplicationReadyEvent。

在這之後就沒有運行期的主要事件了(不考慮 devtools 重啓)。

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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章