spring的启动流程如下所示:
对于该流程图,解释如下:
- 1-SpringApplication(ResourceLoader, Class<?>[])
- 2-读取classpath下所有jar包内META-INF/spring.factories文件
- 3-实例化:Bootstrapper、ApplicationContextInitializer、ApplicationListener
- 5-这一步的最佳实践是:调用入参applicationContext的addBeanFactoryPostProcessor函数,也即注册自定义的BeanFactoryPostProcessor
- 6-这一步中,会遍历AbstractApplicationContext内的列表:beanFactoryPostProcessors,并且当且仅当某一个BeanFactoryPostProcessor同时还是BeanDefinitionRegistryPostProcessor时,才会执行BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry,这两个接口的继承关系如图所示(beanFactoryPostProcessors列表的添加时机可以看上面第5步):
- 7-先调用所有的ApplicationRunner,再调用所有的CommandLineRunner
spring bean生命周期(来源:spring docs):
- BeanNameAware’s setBeanName
- BeanClassLoaderAware’s setBeanClassLoader
- BeanFactoryAware’s setBeanFactory
- EnvironmentAware’s setEnvironment
- EmbeddedValueResolverAware’s setEmbeddedValueResolver
- ResourceLoaderAware’s setResourceLoader (only applicable when running in an application context)
- ApplicationEventPublisherAware’s setApplicationEventPublisher (only applicable when running in an application context)
- MessageSourceAware’s setMessageSource (only applicable when running in an application context)
- ApplicationContextAware’s setApplicationContext (only applicable when running in an application context)
- ServletContextAware’s setServletContext (only applicable when running in a web application context)
- postProcessBeforeInitialization methods of BeanPostProcessors
- InitializingBean’s afterPropertiesSet
- a custom init-method definition
- postProcessAfterInitialization methods of BeanPostProcessors
On shutdown of a bean factory, the following lifecycle methods apply:
- postProcessBeforeDestruction methods of DestructionAwareBeanPostProcessors
- DisposableBean’s destroy
- a custom destroy-method definition