spring boot 启动源码解析系列四:实例化 applicationlistener

SpringApplication initialize 方法:

1
2
3
4
5
6
7
8
9
10
private void (Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}

this.webEnvironment = this.deduceWebEnvironment();
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}

setListeners 方法即找到 ApplicationListener 类并实例化

ApplicationListener 是 Spring 框架中事件监听器接口,即 SpringApplicationRunListener 发布通知事件时,由 ApplicationListener 负责接收。具体可以参考 Spring 事件监听机制。

1
2
3
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E var1);
}

后续的过程和 ApplicationContextInitializer 实现类的实例化无太大差异。

ApplicationListener 在 SpringBoot 中包含两块:

spring-boot-x.x.x.RELEASE.jar/META-INF/spring.factories中:

1
2
3
4
5
6
7
8
9
10
11
# Application Listeners
org.springframework.context.ApplicationListener=
org.springframework.boot.ClearCachesApplicationListener,
org.springframework.boot.builder.ParentContextCloserApplicationListener,
org.springframework.boot.context.FileEncodingApplicationListener,
org.springframework.boot.context.config.AnsiOutputApplicationListener,
org.springframework.boot.context.config.ConfigFileApplicationListener,
org.springframework.boot.context.config.DelegatingApplicationListener,
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener,
org.springframework.boot.logging.ClasspathLoggingApplicationListener,
org.springframework.boot.logging.LoggingApplicationListener

spring-boot-autoconfigure-x.x.x.RELEASE.jar/META-INF/spring.factories中:

1
2
3
# Application Listeners
org.springframework.context.ApplicationListener=
org.springframework.boot.autoconfigure.BackgroundPreinitializer