SpringBoot 2.2.2 源码(二):运行流程一

SpringBoot源码(一)
SpringBoot 2.2.2 源码(二):运行流程一
在上一篇文章里,介绍了SpringBoot的初始化,在这一章节里将介绍run方法里面的内容

跟踪进入run方法

SpringBoot 2.2.2 源码(二):运行流程一

StopWatch

该函数主要用来计算SpringBoot的启动时间

ConfigurableApplicationContext

接下来创建了一个ConfigurableApplicationContext对象,这个对象存储的是SpringBoot的上下文环境,目前还是null

SpringBootExceptionReporter

创建一个SpringBoot的异常报告信息集合

configureHeadlessProperty

这个不重要,主要是为了给一些没有图形化界面的系统或者工具提供图形化界面的

SpringApplicationRunListeners

创建一个运行时的监听器,监听SpringApplication,该对象用集合存储

getRunListeners

SpringBoot 2.2.2 源码(二):运行流程一

这里面又出现了SpringFactoriesInstances,不做赘述,参考SpringBoot源码(一)

listeners的size为1,存储EventPublishingRunListener

目前,在ApplicationListener构造方法中(SpringBoot源码(一))注册了11个Listener,加上运行时SpringApplicationRunListeners中的EventPublishingRunListener,一共12个

listeners.starting()

SpringBoot 2.2.2 源码(二):运行流程一

在这里,拿到了EventPublishingRunListener实例,该监听器比较重要

并且在EventPublishingRunListener的构造方法中完成了11个ApplicationListeners的初始化,如下图

SpringBoot 2.2.2 源码(二):运行流程一
SpringBoot 2.2.2 源码(二):运行流程一

初始化后的11个ApplicationListeners放在了defaultRetriever.applicationListeners中

SpringBoot 2.2.2 源码(二):运行流程一
遍历SpringApplicationRunListeners,将每一个Listenner启动,这里只有一个EventPublishingRunListener

ApplicationStartingEvent

SpringBoot 2.2.2 源码(二):运行流程一
创建ApplicationStartingEvent对象

multicastEvent

SpringBoot 2.2.2 源码(二):运行流程一

传入的参数event 和 eventType都为ApplicationStartingEvent

getApplicationListeners

SpringBoot 2.2.2 源码(二):运行流程一

SpringBoot 2.2.2 源码(二):运行流程一
创建一个ListenerCacheKey对象

retrieverCache.get(cacheKey)

retrieverCache是一个ConcurrentHashMap,目前里边什么都没有,因此retriever = null

进入以下代码

SpringBoot 2.2.2 源码(二):运行流程一
获取retrievalMutex这把锁,目前retrieval还是null,跳过if判断

创建ListenerRetrieval

SpringBoot 2.2.2 源码(二):运行流程一

retrieveApplicationListeners

SpringBoot 2.2.2 源码(二):运行流程一
SpringBoot 2.2.2 源码(二):运行流程一

可以看到在defaultRetriever中含有11个ApplicationListeners

SpringBoot 2.2.2 源码(二):运行流程一

接下来循环遍历这11个ApplicationListeners,看是否支持event,因为监听器只能监听特定类型event

遍历结束,最终有4个匹配的Listener

SpringBoot 2.2.2 源码(二):运行流程一
目前listenerBeans为null,该段代码不执行

SpringBoot 2.2.2 源码(二):运行流程一
最后,对listener排序,清空retriever.applicationListeners,并把刚刚4个listener加进去,返回匹配的4个Listener集合,到此retrieveApplicationListeners方法结束

SpringBoot 2.2.2 源码(二):运行流程一
将cacheKey和retriever放入缓存中,返回4个ApplicationListeners集合,到此getApplicationListeners方法结束

回到multicastEvent方法

SpringBoot 2.2.2 源码(二):运行流程一
遍历4个ApplicationListeners

第一个LoggingApplicationListener,从字面可以看出这是操作日志的。

不断追溯,可以看到以下日志初始化内容:
SpringBoot 2.2.2 源码(二):运行流程一
可以看出,这里设置了默认的日志系统

第二个BackgroundPreinitializer

SpringBoot 2.2.2 源码(二):运行流程一

这里进行了一系列的初始化

第三个DelegatingApplicationListener

跟踪源码,发现里边各种if条件都不满足,所以什么都没做

第四个LiquibaseServiceLocatorApplicationListener

同第三个,什么都没做

到此listeners.starting()返回

SpringBoot 2.2.2 源码(二):运行流程一