相关代码在: https://github.com/chanjarster/spring-boot-all-callbacks
注:本文基于spring-boot 1.4.1.RELEASE, spring 4.3.3.RELEASE撰写。
启动顺序
Spring boot的启动代码一般是这样的:
@SpringBootApplication public class SampleApplication { public static void main(String[] args) throws Exception { SpringApplication.run(SampleApplication.class, args); } }
初始化SpringApplication
SpringApplication#run(Object source, String... args)
#L1174SpringApplication(sources)
#L236SpringApplication#initialize(Object[] sources)
#L256 javadocSpringApplication
利用source来构建Bean。一般来说在run
的时候城市把@SpringBootApplication标志的类(本例中是SampleApplication)放到sources
参数里,然后由这个类出发找到Bean的界说。SpringApplication#run(args)
#L297,进入运行阶段推送ApplicationStartedEvent
SpringApplication#run(args)
#L297
筹备Environment
SpringApplication#run(args)
#L297->#L308->prepareEnvironment(...)
#L331筹备ConfigurableEnvironment。
可以参考官方文档相识StandardEnvironment构建好之后,其MutablePropertySources内部到底有些啥东东。
建设及筹备ApplicationContext
SpringApplication#run(args)
#L297
SpringApplication#createApplicationContext()
#L583建设ApplicationContext。可以看到实际上建设的是AnnotationConfigApplicationContext或AnnotationConfigEmbeddedWebApplicationContext。SpringApplication#prepareContext(...)
#L344筹备ApplicationContextcontext.setEnvironment(environment)
,把之前筹备好的Environment塞给ApplicationContextpostProcessApplicationContext(context)
#L605,给ApplicationContext配置了一些其他对象applyInitializers(context)
#L630,挪用之前筹备好的ApplicationContextInitializerlisteners.contextPrepared(context)
->EventPublishingRunListener.contextPrepared,但实际上啥都没做。load
#L687,认真将source(复数)里所界说的Bean加载到ApplicationContext里,在本例中就是SampleApplication,这些source是在初始化SpringApplication阶段得到的。listeners.contextLoaded(context)
->EventPublishingRunListener.contextLoaded。要留意的是在这个阶段,ApplicationContext里只有SampleApplication,SampleApplication是Bean的加载事情的起点。
刷新ApplicationContext
按照前面所讲,这里的ApplicationContext实际上是GenericApplicationContext ->AnnotationConfigApplicationContext可能AnnotationConfigEmbeddedWebApplicationContext