之前分析过Spring的初始化过程,现在由于微服务的流行,大家纷纷用起了SpringBoot,为了跟上潮流,这里也简单分析一下SpringBoot的启动过程。
使用springboot启动一个微服务十分简单,只需要在启动类上调用SpringApplication的run方法即可。

我们进入run方法进行分析,最终会调用如下方法



我们看到在调用run方法之前会实例化一个SpringApplication,在其的构造函数中会调用initialize方法,该主要有俩个作用,判断该应用是否是web应用以及设置初始化与监听器集合。在META-INF下的spring.factories文件中我们可以看到相应的Initializers类与Listeners类名。
继续分析,来到主要的run方法。

先来说一下前半部分,StopWatch用于记录启动时长,启动SpringApplicationRunListeners监听器,printBanner用于打印项目启动时控制台输出的图像(推荐一个将图片转化为字符的网站http://www.degraeve.com/img2txt.php 我们可以将自己的头像自定义成banner),自定义banner比较简单,不详说了。注册失败分析器等。
接下来是比较重要的三个步骤了,我们一一分析。
首先是prepareContext方法。

可以看到这里主要做一些事前准备工作,包括设置环境变量,执行Initializers的初始化方法,执行监听器的prepare方法,注册springboot特有的一些单例bean等。
第二个步骤是refreshContext,创建新的context容器


我们一步步跟进去发现,最终会调用refresh方法,如果熟悉spring的同学应该对这个方法比较熟悉了,springboot最终也会调用到spring初始化的逻辑中,关于refresh方法内部的分析,可以看我之前写的文章,这里不再赘述。
最后一个步骤afterRefresh

找出容器中的ApplicationRunner与CommandLineRunner并执行其的run方法,我们可以实现自己的runner用于执行一些程序启动自定义逻辑。
经历这三个步骤之后,接下来是一些收尾工作,停止计时,调用监听器finish方法等,最终返回新建的context对象。
到这里主要的初始化逻辑已经分析完了。其实springboot和spring基本是一样的,熟悉spring的同学应该会很容易上手springboot的源码。
网友评论