0%

spring启动流程分析

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):

  1. BeanNameAware’s setBeanName
  2. BeanClassLoaderAware’s setBeanClassLoader
  3. BeanFactoryAware’s setBeanFactory
  4. EnvironmentAware’s setEnvironment
  5. EmbeddedValueResolverAware’s setEmbeddedValueResolver
  6. ResourceLoaderAware’s setResourceLoader (only applicable when running in an application context)
  7. ApplicationEventPublisherAware’s setApplicationEventPublisher (only applicable when running in an application context)
  8. MessageSourceAware’s setMessageSource (only applicable when running in an application context)
  9. ApplicationContextAware’s setApplicationContext (only applicable when running in an application context)
  10. ServletContextAware’s setServletContext (only applicable when running in a web application context)
  11. postProcessBeforeInitialization methods of BeanPostProcessors
  12. InitializingBean’s afterPropertiesSet
  13. a custom init-method definition
  14. postProcessAfterInitialization methods of BeanPostProcessors

On shutdown of a bean factory, the following lifecycle methods apply:

  1. postProcessBeforeDestruction methods of DestructionAwareBeanPostProcessors
  2. DisposableBean’s destroy
  3. a custom destroy-method definition