本文涉及到Spring的监听器,如果不太了解请先阅读之前的Spring监听器的文章。
SpringBoot中默认定义了11个事件监听器对象,全部定义在META-INF/spring.factories文件中。分别是:
org.springframework.boot.ClearCachesApplicationListenerorg.springframework.boot.builder.ParentContextCloserApplicationListenerorg.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessororg.springframework.boot.context.FileEncodingApplicationListenerorg.springframework.boot.context.config.AnsiOutputApplicationListenerorg.springframework.boot.context.config.ConfigFileApplicationListenerorg.springframework.boot.context.config.DelegatingApplicationListenerorg.springframework.boot.context.logging.ClasspathLoggingApplicationListenerorg.springframework.boot.context.logging.LoggingApplicationListenerorg.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListenerorg.springframework.boot.autoconfigure.BackgroundPreinitializer在SpringApplication的构造方法中会对这些默认的事件监听器进行实例化并且给this.listeners属性赋值。代码如下:
// 从spring.factories 文件中获取 ApplicationListener 监听器的实现类setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));SpringApplicationRunListeners 对象初始化,在SpringApplication.run()方法中会根据spring.factories文件中配置的SpringApplicationRunListener接口和已经创建好的SpringApplication对象来创建SpringApplicationRunListener 对象,最终会赋给SpringApplicationRunListeners 对象的this.listeners属性。代码如下:
// 生成事件发布对象// 创建 SpringApplicationRunListeners 并把 默认的事件监听器赋值给 该对象// 从 spring.factories文件中加载 SpringApplicationRunListener 的接口实现类// 具体加载的是 EventPublishingRunListenerSpringApplicationRunListeners listeners = getRunListeners(args);SpringApplicationRunListener 在spring.factories文件中配置为EventPublishingRunListener对象。代码如下:
org.springframework.boot.SpringApplicationRunListener=\org.springframework.boot.context.event.EventPublishingRunListenerEventPublishingRunListener 中会创建具体的多播器对象SimpleApplicationEventMulticaster,会把SpringApplication对象赋值给this.application属性,会把SpringApplication对象中的事件监听器集合遍历赋值给多播器里面的事件监听器集合。代码如下:
public EventPublishingRunListener(SpringApplication application, String[] args) { this.application = application; this.args = args; // 创建多播器 this.initialMulticaster = new SimpleApplicationEventMulticaster(); for (ApplicationListener<?> listener : application.getListeners()) { this.initialMulticaster.addApplicationListener(listener); }}至此,SpringBoot的事件监听发布器初始化完成。
整个SpringBoot的事件监听器调用过程散布在整个SpringBoot生命周期过程中。总共有8个发布事件的方法,在8个不同的地方调用。

starting事件:在SpringBoot开始创建context之前会调用SpringApplicationRunListeners的starting()方法,发布starting事件,在EventPublishingRunListener中代码如下:
@Overridepublic void starting() { this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));}在多播器中找到所有符合事件类型的事件监听器对象进行缓存。代码如下,
@Overridepublic void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); Executor executor = getTaskExecutor(); // 查找符合要求的事件监听器,进行调用 for (ApplicationListener<?> listener : getApplicationListeners(event, type)) { if (executor != null) { executor.execute(() -> invokeListener(listener, event)); } else { invokeListener(listener, event); } }}getApplicationListeners中会根据事件监听器对象和事件类型在多播器的监听器对象中查找满足条件的事件监听器对象,并进行缓存
invokeListener 先判断是否有设置错误处理程序,如果有则需要用错误处理程序来处理事件监听器中发生的异常。
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) { // 获取此多播器的当前错误处理程序 ErrorHandler errorHandler = getErrorHandler(); // 如果errorHandler不为null if (errorHandler != null) { try { // 回调listener的onApplicationEvent方法,传入event doInvokeListener(listener, event); } catch (Throwable err) { // 交给errorHandler接收处理err errorHandler.handleError(err); } } else { // 回调listener的onApplicationEvent方法,传入event doInvokeListener(listener, event); }}doInvokeListener具体调用listener的onApplicationEvent方法,传入event。
/*** 回调listener的onApplicationEvent方法,传入 event* @param listener* @param event*/@SuppressWarnings({"rawtypes", "unchecked"})private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) { try { //回调listener的onApplicationEvent方法,传入 event:contextrefreshListener:onapplicaitonEvent:FrameworkServlet.this.onApplicationEvent() listener.onApplicationEvent(event); } catch (ClassCastException ex) { //获取异常信息 String msg = ex.getMessage(); if (msg == null || matchesClassCastMessage(msg, event.getClass())) { // Possibly a lambda-defined listener which we could not resolve the generic event type for // -> let's suppress the exception and just log a debug message. Log logger = LogFactory.getLog(getClass()); if (logger.isTraceEnabled()) { logger.trace("Non-matching event type for listener: " + listener, ex); } } else { //抛出异常 throw ex; } }}environmentPrepared事件:环境变量准备事件,在创建好环境变量之后进行发布。在EventPublishingRunListener中代码如下,
public void environmentPrepared(ConfigurableEnvironment environment) { this.initialMulticaster .multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));}contextPrepared事件:应用程序上下文准备事件,在创建好ApplicationContext之后立马调用。在EventPublishingRunListener中代码如下
public void contextPrepared(ConfigurableApplicationContext context) { this.initialMulticaster .multicastEvent(new ApplicationContextInitializedEvent(this.application, this.args, context));}contextLoaded事件:应用程序上下文加载事件,在主配置类注册到ApplicationContext中之后会进行调用。在进行发布ApplicationPreparedEvent事件之前,先把EventPublishingRunListener 的监听器对象都注入到ApplicationContext中。在EventPublishingRunListener中代码如下
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));}started事件:应用程序启动完成事件,在应用程序完成refresh之后进行调用。在EventPublishingRunListener中代码如下
public void started(ConfigurableApplicationContext context) { context.publishEvent(new ApplicationStartedEvent(this.application, this.args, context));}running事件:应用程序上下文ApplicationContext对象创建好之后进行发布该事件。在EventPublishingRunListener中代码如下
@Overridepublic void running(ConfigurableApplicationContext context) { context.publishEvent(new ApplicationReadyEvent(this.application, this.args, context));}failed事件:在整个SpringBoot对象的生命周期过程,如果出现异常则发布该事件。在EventPublishingRunListener中代码如下
public void failed(ConfigurableApplicationContext context, Throwable exception) { ApplicationFailedEvent event = new ApplicationFailedEvent(this.application, this.args, context, exception); if (context != null && context.isActive()) { // Listeners have been registered to the application context so we should // use it at this point if we can context.publishEvent(event); } else { // An inactive context may not have a multicaster so we use our multicaster to // call all of the context's listeners instead if (context instanceof AbstractApplicationContext) { for (ApplicationListener<?> listener : ((AbstractApplicationContext) context) .getApplicationListeners()) { this.initialMulticaster.addApplicationListener(listener); } } this.initialMulticaster.setErrorHandler(new LoggingErrorHandler()); this.initialMulticaster.multicastEvent(event); }}一般来说我们创建事件监听器只会只用Spring的创建方式,不会用SpringBoot的方式。但是通过代码发现,通过SpringBoot方式创建的事件监听器会自动注入到Spring容器的多播器中。这是怎么做到?一起来分析下。
SpringBoot方式:事件监听器只能通过实现ApplicationListener
Spring方式:事件监听器可以通过实现ApplicationListener
SpringBoot先创建自己的事件发布器对象SpringApplicationRunListeners ,并且在整个生命周期中发布不同事件,然后再把其中的事件监听器添加到应用程序上下文ApplicationContext(Spring容器)中。Spring容器在之后初始化的过程中会把这些事件监听器加载到Spring的多播器中,这样就完成了集成。在SpringBoot启动的生命周期过程中,有两个地方可以对应用程序上下文ApplicationContext进行监听器的创建。
// 初始化 context,在具体的 ApplicationContextInitializer 类中给 context 添加相关的事件监听器applyInitializers(context);在该方法中会遍历执行SpringApplication中创建的ApplicationContextInitializer接口对象。其中RSocketPortInfoApplicationContextInitializer对象和RSocketPortInfoApplicationContextInitializer对象以及ConditionEvaluationReportLoggingListener对象都会对ApplicationContext添加事件监听器。
// 发布 contextLoaded 事件 ,把 SpringApplication 中的事件监听器 添加给 context 的监听器列表listeners.contextLoaded(context);该方法中会先把EventPublishingRunListener 中的监听器对象都注入到ApplicationContext中,再进行发布ApplicationPreparedEvent事件。具体代码在EventPublishingRunListener代码如下,
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));}