Spring系列第55篇:spring上下文生命周期

star2017 1年前 ⋅ 529 阅读

本文主要内容:带大家掌握spring应用上下文的生命周期。

为什么需要掌握这个?

1、应对面试,面试中经常会问到

2、项目中想扩展spring的,那么这部分内容必须掌握

3、更容易阅读spirng源码

1、什么是spring应用上下文?

接口org.springframework.context.ApplicationContext表示spring上下文,下面2个实现类

  1. org.springframework.context.support.ClassPathXmlApplicationContext
  2. org.springframework.context.annotation.AnnotationConfigApplicationContext

2、应用上文生命周期(14个阶段)

1、创建spring应用上下文

2、上下文启动准备阶段

3、BeanFactory创建阶段

4、BeanFactory准备阶段

5、BeanFactory后置处理阶段

6、BeanFactory注册BeanPostProcessor阶段

7、初始化内建Bean:MessageSource

8、初始化内建Bean:Spring事件广播器

9、Spring应用上下文刷新阶段

10、Spring事件监听器注册阶段

11、单例bean实例化阶段

12、BeanFactory初始化完成阶段

13、Spring应用上下文启动完成阶段

14、Spring应用上下文关闭阶段

3、Spring应用上下文的使用

看下这段代码,是不是很熟悉,这就是spring上下文最常见的用法,稍后我们以这段代码为例,结合spring源码,来细说每个阶段的细节。

  1. @Configuration
  2. @ComponentScan
  3. public class MainConfig {
  4. public static void main(String[] args) {
  5. //1.创建spring上下文
  6. AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext();
  7. //2.上下文中注册bean
  8. configApplicationContext.register(MainConfig.class);
  9. //3.刷新spring上下文,内部会启动spring上下文
  10. configApplicationContext.refresh();
  11. //4.关闭spring上下文
  12. System.out.println("stop ok!");
  13. }
  14. }

4、阶段1:创建Spring应用上下文

对应这段代码

  1. AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext();

看一下其类图,这里主要列出了AnnotationConfigApplicationContext2个父类

当调用子类的构造器的时候,默认会自动先调用父类的构造器,先来看一下GenericApplicationContext构造器源码,如下,将beanFactory创建好了。

  1. public GenericApplicationContext() {
  2. this.beanFactory = new DefaultListableBeanFactory();
  3. }

再来看看AnnotationConfigApplicationContext构造器源码,如下:

  1. public AnnotationConfigApplicationContext() {
  2. //创建AnnotatedBeanDefinitionReader:用来读取及注册通过注解方式定义的bean
  3. this.reader = new AnnotatedBeanDefinitionReader(this); //@1
  4. //创建ClassPathBeanDefinitionScanner:bean定义扫描器,可以扫描包中的类,对满足条件的类,会将其注册到spring容器中
  5. this.scanner = new ClassPathBeanDefinitionScanner(this);
  6. }

@1:new AnnotatedBeanDefinitionReader(this),进入这个方法内部,最终会走到下面这个方法,非常关键的一个方法,会向spring容器中注册5个关键的bean,这几个bean都是非常很重要的。

  1. org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object)
  2. public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
  3. BeanDefinitionRegistry registry, @Nullable Object source) {
  4. //1、注册ConfigurationClassPostProcessor,这是个非常关键的类,实现了BeanDefinitionRegistryPostProcessor接口
  5. // ConfigurationClassPostProcessor这个类主要做的事情:负责所有bean的注册,如果想看bean注册源码的,可以在其postProcessBeanDefinitionRegistry方法中设置断点
  6. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  7. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  8. def.setSource(source);
  9. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
  10. }
  11. //2、注册AutowiredAnnotationBeanPostProcessor:负责处理@Autowire注解
  12. if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  13. RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
  14. def.setSource(source);
  15. beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
  16. }
  17. //3、注册CommonAnnotationBeanPostProcessor:负责处理@Resource注解
  18. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  19. RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
  20. def.setSource(source);
  21. beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
  22. }
  23. //4、注册EventListenerMethodProcessor:负责处理@EventListener标注的方法,即事件处理器
  24. if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
  25. RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
  26. def.setSource(source);
  27. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
  28. }
  29. //5、注册DefaultEventListenerFactory:负责将@EventListener标注的方法包装为ApplicationListener对象
  30. if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
  31. RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
  32. def.setSource(source);
  33. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
  34. }
  35. return beanDefs;
  36. }

再来捋一下上面这段代码,主要向spring容器中注册了5个关键的bean

1、ConfigurationClassPostProcessor:这是个非常关键的类,建议去看一下他的源码,基本上我们自定义的bean都是通过这个类注册的,下面这些注解都是在这个类中处理的

  1. @Configuration
  2. @Component
  3. @PropertySource
  4. @PropertySources
  5. @ComponentScan
  6. @ComponentScans
  7. @Import
  8. @ImportResource
  9. @Bean

2、AutowiredAnnotationBeanPostProcessor:负责处理@Autowire注解

3、注册CommonAnnotationBeanPostProcessor:负责处理@Resource注解

4、注册EventListenerMethodProcessor:负责处理@EventListener标注的方法,即事件处理器

5、注册DefaultEventListenerFactory:负责将@EventListener标注的方法包装为ApplicationListener对象

5、阶段2~阶段13

阶段2到阶段13,这中间的12个阶段都位于refresh方法中,所以refresh方法非常很重要,需要多花时间研究这个方法。

refresh方法源码如下:

  1. org.springframework.context.support.AbstractApplicationContext#refresh
  2. @Override
  3. public void refresh() throws BeansException, IllegalStateException {
  4. // 阶段2:Spring应用上下文启动准备阶段
  5. prepareRefresh();
  6. // 阶段3:BeanFactory创建阶段
  7. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  8. // 阶段4:BeanFactory准备阶段
  9. prepareBeanFactory(beanFactory);
  10. try {
  11. // 阶段5:BeanFactory后置处理阶段
  12. postProcessBeanFactory(beanFactory);
  13. // 阶段6:BeanFactory注册BeanPostProcessor阶段
  14. invokeBeanFactoryPostProcessors(beanFactory);
  15. // 阶段7:注册BeanPostProcessor
  16. registerBeanPostProcessors(beanFactory);
  17. // 阶段8:初始化内建Bean:MessageSource
  18. initMessageSource();
  19. // 阶段9:初始化内建Bean:Spring事件广播器
  20. initApplicationEventMulticaster();
  21. // 阶段10:Spring应用上下文刷新阶段,由子类实现
  22. onRefresh();
  23. // 阶段11:Spring事件监听器注册阶段
  24. registerListeners();
  25. // 阶段12:实例化所有剩余的(非lazy init)单例。
  26. finishBeanFactoryInitialization(beanFactory);
  27. // 阶段13:刷新完成阶段
  28. finishRefresh();
  29. }
  30. }

6、阶段2:Spring应用上下文启动准备阶段

  1. protected void prepareRefresh() {
  2. // 标记启动时间
  3. this.startupDate = System.currentTimeMillis();
  4. // 是否关闭:false
  5. this.closed.set(false);
  6. // 是否启动:true
  7. this.active.set(true);
  8. // 初始化PropertySource,留个子类去实现的,可以在这个方法中扩展属性配置信息,丢到this.environment中
  9. initPropertySources();
  10. // 验证环境配置中是否包含必须的配置参数信息,比如我们希望上下文启动中,this.environment中必须要有某些属性的配置,才可以启动,那么可以在这个里面验证
  11. getEnvironment().validateRequiredProperties();
  12. // earlyApplicationListeners用来存放早期的事件监听器
  13. if (this.earlyApplicationListeners == null) {
  14. this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
  15. }
  16. else {
  17. // Reset local application listeners to pre-refresh state.
  18. this.applicationListeners.clear();
  19. this.applicationListeners.addAll(this.earlyApplicationListeners);
  20. }
  21. // earlyApplicationEvents用来存放早期的事件
  22. this.earlyApplicationEvents = new LinkedHashSet<>();
  23. }

这里说一下什么是早期事件?什么是早期的事件监听器呢?

当使用spring上下文发布事件的时候,如下代码

  1. applicationContext.publishEvent(事件对象)

其内部最终会用到AbstractApplicationContext下面这个属性来发布事件,但是可能此时applicationEventMulticaster还没有创建好,是空对象,所以此时是无法广播事件的,那么此时发布的时间就是早期的时间,就会被放在this.earlyApplicationEvents中暂时存放着,当时间广播器applicationEventMulticaster创建好了之后,才会会将早期的事件广播出去

  1. private ApplicationEventMulticaster applicationEventMulticaster;

同理,当applicationEventMulticaster还未准备好的时候,调用下面下面代码向spring上下文中添加事件监听器的时候,这时放进去的监听器就是早期的事件监听器。

  1. applicationContext.addApplicationListener(事件监听器对象)

说了这么多,理解起来很简单,就是当事件广播器applicationEventMulticaster还未准备好的时候,此时向上下文中添加的事件就是早期的事件,会被放到this.earlyApplicationEvents中,此时这个事件暂时没办法广播。

7、阶段3:BeanFactory创建阶段

这个阶段负责将BeanFactory创建好,返回给spring应用上下文

  1. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

obtainFreshBeanFactory源码:

  1. protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  2. //刷新BeanFactory,由子类实现
  3. refreshBeanFactory();
  4. //返回spring上下文中创建好的BeanFacotry
  5. return getBeanFactory();
  6. }

8、阶段4:BeanFactory准备阶段

  1. prepareBeanFactory(beanFactory);

8.1、源码

  1. protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  2. // 设置类加载器
  3. beanFactory.setBeanClassLoader(getClassLoader());
  4. // 设置spel表达式解析器
  5. beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  6. // 设置属性编辑器注册器
  7. beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
  8. // @1:添加一个BeanPostProcessor:ApplicationContextAwareProcessor,当你的bean实现了spring中xxxAware这样的接口,那么bean创建的过程中,将由ApplicationContextAwareProcessor来回调这些接口,将对象注入进去
  9. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
  10. // @2:自动注入的时候,下面这些接口定义的方法,将会被跳过自动注入,为什么?因为这部分接口将由ApplicationContextAwareProcessor来回调注入
  11. beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
  12. beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
  13. beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
  14. beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
  15. beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
  16. beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
  17. // @3:注册依赖注入的时候查找的对象,比如你的bean中想用ResourceLoader,那么可以写:@Autowire private ResourceLoader resourceLoader,那么spring容器会将spring容器上下文注入进去
  18. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
  19. beanFactory.registerResolvableDependency(ResourceLoader.class, this);
  20. beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
  21. beanFactory.registerResolvableDependency(ApplicationContext.class, this);
  22. // @4:注入一个beanpostprocessor:ApplicationListenerDetector
  23. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
  24. // @5:将Environment注册到spring容器,对应的bena名称是environment
  25. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
  26. beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
  27. }
  28. // @6:将系统属性注册到spring容器,对应的bean名称是systemProperties
  29. if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
  30. beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
  31. }
  32. // @7:将系统环境变量配置信息注入到spring容器,对应的bean名称是systemEnvironment
  33. if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
  34. beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
  35. }
  36. }

8.2、先来看看@1的代码

  1. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

向spring容器中注入了一个ApplicationContextAwareProcessor,这是一个BeanPostProcessor(Bean处理器),这个接口中定义了很多方法,会在bean创建的不同阶段被调用,常用来扩展bean的创建过程。想升入了解的朋友,可以先去看一下这篇文章:Bean生命周期

在回到ApplicationContextAwareProcessor这个接口上来,看一下其的源码,大家就知道是干什么的,如下,当我们的bean实现了Aware这样的接口的时候,接口中的方法会被回调,用来在自定义的bean中注入spring上下文中的一些对象,比如我们在我们的bean中用到Environment,那么只需实现EnvironmentAware接口,那么Environment会被自动注入进去

  1. if (bean instanceof EnvironmentAware) {
  2. ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
  3. }
  4. if (bean instanceof EmbeddedValueResolverAware) {
  5. ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
  6. }
  7. if (bean instanceof ResourceLoaderAware) {
  8. ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
  9. }
  10. if (bean instanceof ApplicationEventPublisherAware) {
  11. ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
  12. }
  13. if (bean instanceof MessageSourceAware) {
  14. ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
  15. }
  16. if (bean instanceof ApplicationContextAware) {
  17. ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
  18. }

8.3、再来看看@3的代码

  1. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
  2. beanFactory.registerResolvableDependency(ResourceLoader.class, this);
  3. beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
  4. beanFactory.registerResolvableDependency(ApplicationContext.class, this);

这个用来向spring容器中添加依赖查找的对象,上面代码的第1行是添加了BeanFactory,当我们的bean中想用到BeanFactory的时候,只需要按照下面这么写,那么就会被自动注入,即使因为上面第1行代码将BeanFactory添加到依赖查找列表中了

  1. @Autowire
  2. private BeanFactory beanFactory;

8.4、再来看看@4的代码

  1. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

ApplicationListenerDetector也是一个BeanPostProcessor,这个类是干嘛的?处理自定义的事件监听器的。

当我们的bean实现了ApplicationListener接口,是一个事件监听器的时候,那么这个bean创建的过程中将会被ApplicationListenerDetector处理,会将我们这个bean添加到spring上下文容器的事件监听器列表中。

8.5、再来看看@5的代码

  1. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
  2. beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
  3. }

将Environment作为单例注册到spring容器单例列表中,对应的bena名称是environment,当我们的bean中需要用到Environment的时候,可以使用下面的写法,此时spring容器创建bean的过程中,就会从单例的bean列表中找到Environment,将其注入到下面的属性中。

  1. @Autowire
  2. private Environment environment

我们还可以通过environment名称从spring容器中查找到Environment对象,如下:

  1. applicationContext.getBean("environment", Environment.class)

8.6、再来看看@6、@7代码

这个同@5的代码,这里说一下

  1. getEnvironment().getSystemProperties() -- 对应 --> System.getProperties()
  2. getEnvironment().getSystemEnvironment() -- 对应 --> System.getenv()

这里说一下System.getProperties()、System.getenv()这两个是干嘛的。

下面这个命令大家都用过吧,大家主要看一下-D,这个可以设置一些启动参数,-D后面跟的这些参数,会被放在System.getProperties()中了。

  1. java -jar -D参数=值

System.getenv()用来获取环境变量信息的。

9、阶段5:BeanFactory后置处理阶段

  1. postProcessBeanFactory(beanFactory);

这个方法留给子类实现的,此时beanFactory已经创建好了,但是容器中的bean还没有被实例化,子类可以实现这个方法,可以对BeanFactory做一些特殊的配置,比如可以添加一些自定义BeanPostProcessor等等,主要是留给子类去扩展的。

10、阶段6:BeanFactory注册BeanPostProcessor阶段

  1. invokeBeanFactoryPostProcessors(beanFactory);

调用BeanFactoryPostProcessor,BeanFactoryPostProcessor是干什么的?

建议一定要先看一下这篇文章:Spring系列第29篇:BeanFactory扩展(BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor)

这个阶段主要就是从spring容器中找到BeanFactoryPostProcessor接口的所有实现类,然后调用,完成所有bean注册的功能,注意是bean注册,即将bean的定义信息转换为BeanDefinition对象,然后注册到spring容器中,此时bean还未被实例化,下面继续。

大家再回头看一下阶段1,阶段1在spring容器中注册了一个非常关键的bean:ConfigurationClassPostProcessor,代码如下

  1. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
  2. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
  3. def.setSource(source);
  4. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
  5. }

ConfigurationClassPostProcessor就实现了BeanFactoryPostProcessor接口,所以ConfigurationClassPostProcessor会在阶段6中被调用,下面这些注解都是在这个类中处理的,所以想研究下面这些注解原理的,直接看去看ConfigurationClassPostProcessor的源码,非常关键重要的一个类,研究spring源码,此类必看

  1. @Configuration
  2. @Component
  3. @PropertySource
  4. @PropertySources
  5. @ComponentScan
  6. @ComponentScans
  7. @Import
  8. @ImportResource
  9. @Bean

通常,阶段6执行完毕之后,我们所有自定义的bean都已经被注册到spring容器中了,被转换为BeanDefinition丢到BeanFactory中了,此时bean还未被实例化。

11、阶段7:注册BeanPostProcessor

  1. registerBeanPostProcessors(beanFactory);

注册BeanPostProcessor,这个阶段会遍历spring容器bean定义列表,把所有实现了BeanPostProcessor接口的bean撸出来,然后将他们添加到spring容器的BeanPostProcessor列表中。

BeanPostProcessor是bean后置处理器,其内部提供了很多方法,用来对bean创建的过程进行扩展的。

12、阶段8:初始化内建Bean:MessageSource

  1. initMessageSource();

MessageSource 是用来处理国际化的,这个阶段会将MessageSource创建好,如果想扩展或者实现国家化的,可以看看这个方法的源码。

关于国际化的可以看这篇文章:

13、阶段9:初始化内建Bean:Spring事件广播器

  1. initApplicationEventMulticaster();

ApplicationEventMulticaster是事件广播器,用来广播事件的,这个阶段会将ApplicationEventMulticaster创建好,如果想自定义事件广播器的,可以看看这个方法的源码,关于spring事件的使用,看这里:。

14、阶段10:Spring应用上下文刷新阶段,由子类实现

  1. onRefresh();

用来初始化其他特殊的bean,由子类去实现。

15、阶段11:Spring事件监听器注册阶段

  1. registerListeners();

注册事件监听器到事件广播器中,看一下其源码,如下:

  1. protected void registerListeners() {
  2. // @1:先注册静态指定的侦听器,即将spring上下文中添加的时间监听器,添加到时间广播器(ApplicationEventMulticaster)中
  3. for (ApplicationListener<?> listener : getApplicationListeners()) {
  4. getApplicationEventMulticaster().addApplicationListener(listener);
  5. }
  6. // @2:将spring容器中定义的事件监听器,添加到时间广播器(ApplicationEventMulticaster)中
  7. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  8. for (String listenerBeanName : listenerBeanNames) {
  9. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  10. }
  11. // @3:此时事件广播器准备好了,所以此时发布早期的事件(早期的事件由于事件广播器还未被创建,所以先被放在了earlyApplicationEvents中,而此时广播器创建好了,所以将早期的时间发布一下)
  12. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  13. this.earlyApplicationEvents = null;
  14. if (earlyEventsToProcess != null) {
  15. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  16. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  17. }
  18. }
  19. }

这里主要说一下@1,将上下文中的事件监听器添加到事件广播器中,看看下面源码就懂了

  1. org.springframework.context.support.AbstractApplicationContext
  2. Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
  3. public Collection<ApplicationListener<?>> getApplicationListeners() {
  4. return this.applicationListeners;
  5. }
  6. @Override
  7. public void addApplicationListener(ApplicationListener<?> listener) {
  8. Assert.notNull(listener, "ApplicationListener must not be null");
  9. if (this.applicationEventMulticaster != null) {
  10. this.applicationEventMulticaster.addApplicationListener(listener);
  11. }
  12. this.applicationListeners.add(listener);
  13. }

再来看看@3,广播早期的事件,早期的时候,由于事件广播器this.applicationEventMulticaster还是空,所以事件被放在了this.earlyApplicationEvents这个集合中并没有广播,等到这个时候才广播早期的事件,所以用事件的时候,大家需要注意,如果你在阶段11之前,调用了下面方法发布事件,那么可能此时你看不到事件产生的效果

  1. applicationContext.publishEvent(事件对象)

所以如果你的bean实现了下面这些接口,不建议再实现org.springframework.context.ApplicationListener接口,否则会让你莫名其妙的感觉。

  1. org.springframework.beans.factory.config.BeanFactoryPostProcessor
  2. org.springframework.beans.factory.config.BeanPostProcessor

16、阶段12:实例化所有剩余的(非lazy init)单例

  1. finishBeanFactoryInitialization(beanFactory);

这个方法中将实例化所有单例的bean(不包需要延迟实例化的bean),来看看其源码:

  1. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  2. // 添加${}表达式解析器
  3. if (!beanFactory.hasEmbeddedValueResolver()) {
  4. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  5. }
  6. // 冻结所有bean定义,表示已注册的bean定义不会被进一步修改或后处理。这允许工厂主动缓存bean定义元数据。
  7. beanFactory.freezeConfiguration();
  8. // @1:实例化所有单例bean(不包含需延迟实例化的bean),通常scope=singleton的bean都会在下面这个方法中完成初始化。
  9. beanFactory.preInstantiateSingletons();
  10. }

重点看@1的代码,这里会调用beanFactory的preInstantiateSingletons()方法,进去看源码,源码位于DefaultListableBeanFactory这个类中,如下:

  1. org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
  2. public void preInstantiateSingletons() throws BeansException {
  3. // beanDefinitionNames表示当前BeanFactory中定义的bean名称列表,
  4. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  5. // @1:循环实例化bean
  6. for (String beanName : beanNames) {
  7. //这里根据beanName来来实例化bean,代码省略了。。。。
  8. }
  9. // @2:变量bean,若bean实现了SmartInitializingSingleton接口,将调用其afterSingletonsInstantiated()方法
  10. for (String beanName : beanNames) {
  11. Object singletonInstance = getSingleton(beanName);
  12. if (singletonInstance instanceof SmartInitializingSingleton) {
  13. final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
  14. smartSingleton.afterSingletonsInstantiated();
  15. }
  16. }
  17. }

上面这个方法主要做了2个事情:

1、完成所有单例bean的实例化:对应上面的代码@1,循环遍历beanNames列表,完成所有单例bean的实例化工作,这个循环完成之后,所有单例bean已经实例化完毕了,被放在spring容器缓存起来了。

2、回调SmartInitializingSingleton接口:对应上面的代码@2,此时所有的单例bean已经实例化好了,此时遍历所有单例bean,若bean实现了SmartInitializingSingleton接口,这个接口中有个afterSingletonsInstantiated方法,此时会回调这个方法,若我们想在所有单例bean创建完毕之后,做一些事情,可以实现这个接口。

17、阶段13:刷新完成阶段

  1. finishRefresh();

17.1、源码

  1. protected void finishRefresh() {
  2. // @1:清理一些资源缓存
  3. clearResourceCaches();
  4. // @2:为此上下文初始化生命周期处理器
  5. initLifecycleProcessor();
  6. // @3:首先将刷新传播到生命周期处理器
  7. getLifecycleProcessor().onRefresh();
  8. // @4:发布ContextRefreshedEvent事件
  9. publishEvent(new ContextRefreshedEvent(this));
  10. }

17.2、先来看@2的代码

  1. initLifecycleProcessor();

源码如下

  1. protected void initLifecycleProcessor() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. //spring容器中是否有名称为"lifecycleProcessor"的bean
  4. if (beanFactory.containsLocalBean("lifecycleProcessor")) {
  5. //从spring容器中找到LifecycleProcessor,赋给this.lifecycleProcessor
  6. this.lifecycleProcessor =
  7. beanFactory.getBean("lifecycleProcessor", LifecycleProcessor.class);
  8. }
  9. else {
  10. //如果spring容器中没有自定义lifecycleProcessor,那么创建一个默认的DefaultLifecycleProcessor
  11. DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
  12. defaultProcessor.setBeanFactory(beanFactory);
  13. //设置当前spring应用上下文的生命周期处理器
  14. this.lifecycleProcessor = defaultProcessor;
  15. //将其注册到spring容器中
  16. beanFactory.registerSingleton("lifecycleProcessor", this.lifecycleProcessor);
  17. }
  18. }

17.3、再来看@3的代码

  1. getLifecycleProcessor().onRefresh();

调用LifecycleProcessoronRefresh方法, 这里要先说一下org.springframework.context.LifecycleProcessor这个接口,生命周期处理器,接口中定义了2个方法,而onClose方法会在上下文关闭中会被调用,稍后会看到

  1. public interface LifecycleProcessor extends Lifecycle {
  2. /**
  3. * 上下文刷新通知
  4. */
  5. void onRefresh();
  6. /**
  7. * 上下文关闭通知
  8. */
  9. void onClose();
  10. }

先来看看onRefresh方法,这个接口有个默认实现org.springframework.context.support.DefaultLifecycleProcessor,所以默认情况下,我们就看DefaultLifecycleProcessor中的onRefresh源码,如下

  1. public void onRefresh() {
  2. startBeans(true);
  3. this.running = true;
  4. }

进入startBeans(true)内部看看,如下,代码看起来可能有点绕,实际上很简单,就是从容器中找到所有实现org.springframework.context.Lifecycle接口的bean,然后调用他们的start方法。

  1. private void startBeans(boolean autoStartupOnly) {
  2. Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
  3. Map<Integer, LifecycleGroup> phases = new HashMap<>();
  4. lifecycleBeans.forEach((beanName, bean) -> {
  5. if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
  6. int phase = getPhase(bean);
  7. LifecycleGroup group = phases.get(phase);
  8. if (group == null) {
  9. group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
  10. phases.put(phase, group);
  11. }
  12. group.add(beanName, bean);
  13. }
  14. });
  15. if (!phases.isEmpty()) {
  16. List<Integer> keys = new ArrayList<>(phases.keySet());
  17. Collections.sort(keys);
  18. for (Integer key : keys) {
  19. phases.get(key).start();
  20. }
  21. }
  22. }

17.4、再来看@4的代码

  1. publishEvent(new ContextRefreshedEvent(this));

发布ContextRefreshedEvent事件,想在这个阶段做点事情的,可以监听这个事件。

17.5、小结下

这个阶段主要干了3个事情:

1、初始化当前上下文中的生命周期处理器LifecycleProcessor。

2、调用LifecycleProcessor.onRefresh()方法,若没有自定义LifecycleProcessor,那么会走DefaultLifecycleProcessor,其内部会调用spring容器中所有实现Lifecycle接口的bean的start方法。

3、发布ContextRefreshedEvent事件。

18、阶段14:Spring应用上下文关闭阶段

18.1、源码

  1. applicationContext.close()

最终会进入到doClouse()方法,代码如下

  1. org.springframework.context.support.AbstractApplicationContext#doClose
  2. protected void doClose() {
  3. // 判断是不是需要关闭(active为tue的时候,才能关闭,并用cas确保并发情况下只能有一个执行成功)
  4. if (this.active.get() && this.closed.compareAndSet(false, true)) {
  5. //@1:发布关闭事件ContextClosedEvent
  6. publishEvent(new ContextClosedEvent(this));
  7. // @2:调用生命周期处理器的onClose方法
  8. if (this.lifecycleProcessor != null) {
  9. this.lifecycleProcessor.onClose();
  10. }
  11. // @3:销毁上下文的BeanFactory中所有缓存的单例
  12. destroyBeans();
  13. // @4:关闭BeanFactory本身
  14. closeBeanFactory();
  15. // @5:就给子类去扩展的
  16. onClose();
  17. // @6:恢复事件监听器列表至刷新之前的状态,即将早期的事件监听器还原
  18. if (this.earlyApplicationListeners != null) {
  19. this.applicationListeners.clear();
  20. this.applicationListeners.addAll(this.earlyApplicationListeners);
  21. }
  22. // @7:标记活动状态为:false
  23. this.active.set(false);
  24. }
  25. }

18.2、先来看@1的代码

  1. publishEvent(new ContextClosedEvent(this));

发布ContextClosedEvent事件。

18.3、再来看@2的代码

  1. if (this.lifecycleProcessor != null) {
  2. this.lifecycleProcessor.onClose();
  3. }

调用生命周期处理器的onClose方法,这里我们直接看DefaultLifecycleProcessor的onClose(),看看其源码,如下

  1. public void onClose() {
  2. stopBeans();
  3. //将running设置为false
  4. this.running = false;
  5. }

stopBeans()源码如下,一大片,简单点理解:就是从容器中找到所有实现org.springframework.context.Lifecycle接口的bean,然后调用他们的close()方法。

  1. private void stopBeans() {
  2. Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
  3. Map<Integer, LifecycleGroup> phases = new HashMap<>();
  4. lifecycleBeans.forEach((beanName, bean) -> {
  5. int shutdownPhase = getPhase(bean);
  6. LifecycleGroup group = phases.get(shutdownPhase);
  7. if (group == null) {
  8. group = new LifecycleGroup(shutdownPhase, this.timeoutPerShutdownPhase, lifecycleBeans, false);
  9. phases.put(shutdownPhase, group);
  10. }
  11. group.add(beanName, bean);
  12. });
  13. if (!phases.isEmpty()) {
  14. List<Integer> keys = new ArrayList<>(phases.keySet());
  15. keys.sort(Collections.reverseOrder());
  16. for (Integer key : keys) {
  17. phases.get(key).stop();
  18. }
  19. }
  20. }

18.4、再来看@3的代码

  1. destroyBeans();

销毁上下文的BeanFactory中所有缓存的单例bean,主要干2件事情:

1、调用bean的销毁方法

比如bean实现了org.springframework.beans.factory.DisposableBean接口,此时会被调用。还有bean中有些方法标注了@PreDestroy注解的,此时也会被调用。

2、将bean的信息从BeanFactory中清理掉

18.5、再来看@4的代码

  1. closeBeanFactory();

源码如下,主要就是想当前spring应用上下文中的beanFactory属性还原。

  1. org.springframework.context.support.AbstractRefreshableApplicationContext#closeBeanFactory
  2. @Override
  3. protected final void closeBeanFactory() {
  4. synchronized (this.beanFactoryMonitor) {
  5. if (this.beanFactory != null) {
  6. this.beanFactory.setSerializationId(null);
  7. this.beanFactory = null;
  8. }
  9. }
  10. }

19、总结

本文详细介绍了spring应用上下文的生命周期,非常重要,内容和细节稍微比较多,建议大家结合源码多看几遍,平时闲的时候,也可以回头再看几遍,加深理解,有问题的欢迎留言交流。

20、案例源码

  1. git地址:
  2. https://gitee.com/javacode2018/spring-series

本博客所有系列案例代码以后都会放到这个上面,大家watch一下,可以持续关注动态。

最新资料

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: