Loading

Spring Bean的生命周期(转载)

转载自weixin_39911567

面试官经常喜欢考察面试者Spring Bean的知识,可见是Spring中重要的内容

Spring Bean的生命周期指的是Bean从创建到初始化再到销毁的过程,这个过程由IOC容器管理。一个完整的Bean生命周期可以参考Spring Bean生命周期。这里我们主要记录一些和Bean生命周期相关的细节。

Bean的初始化和销毁 在整个生命周期过程中,我们可以自定义Bean的初始化和销毁钩子函数,当Bean的生命周期到达相应的阶段的时候,Spring会调用我们自定义的Bean的初始化和销毁方法。自定义Bean初始化和销毁方法有多种方式,下面逐一介绍。

374544735d0dd4104601ef98749c7f89.png


但是当我第一次看到该图时,就产生了很多困扰,“Aware,BeanPostProcessor......这些都是什么啊?而且这么多步骤,太多了,该怎么记啊?”。
其实要记忆该过程,还是需要我们先去理解,本文将从以下两方面去帮助理解 Bean 的生命周期:

  1. 生命周期的概要流程:对 Bean 的生命周期进行概括,并且结合代码来理解;
  2. 扩展点的作用:详细介绍 Bean 生命周期中所涉及到的扩展点的作用。

2. 生命周期的概要流程
Bean 的生命周期概括起来就是 4 个阶段

  1. 实例化(Instantiation)
  2. 属性赋值(Populate)
  3. 初始化(Initialization)
  4. 销毁(Destruction)

e8a473640bcd06e544c86fa729133ac3.png
  1. 实例化:第 1 步,实例化一个 bean 对象;
  2. 属性赋值:第 2 步,为 bean 设置相关属性和依赖;
  3. 初始化:第 3~7 步,步骤较多,其中第 5、6 步为初始化操作,第 3、4 步为在初始化前执行,第 7 步在初始化后执行,该阶段结束,才能被用户使用;
  4. 销毁:第 8~10步,第8步不是真正意义上的销毁(还没使用呢),而是先在使用前注册了销毁的相关调用接口,为了后面第9、10步真正销毁 bean 时再执行相应的方法。

下面我们结合代码来直观的看下,在 doCreateBean() 方法中能看到依次执行了这 4 个阶段:

  1. // AbstractAutowireCapableBeanFactory.java
  2. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
  3. throws BeanCreationException {
  4. // 1. 实例化
  5. BeanWrapper instanceWrapper = null;
  6. if (instanceWrapper == null) {
  7. instanceWrapper = createBeanInstance(beanName, mbd, args);
  8. }
  9. Object exposedObject = bean;
  10. try {
  11. // 2. 属性赋值
  12. populateBean(beanName, mbd, instanceWrapper);
  13. // 3. 初始化
  14. exposedObject = initializeBean(beanName, exposedObject, mbd);
  15. }
  16. // 4. 销毁-注册回调接口
  17. try {
  18. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  19. }
  20. return exposedObject;
  21. }


由于初始化包含了第 3~7 步, 较复杂, 所以我们进到 initializeBean() 方法里具体看下其过程( 注释的序号对应图中序号):

// AbstractAutowireCapableBeanFactory.java protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) { //

3. 检查 Aware 相关接口并设置相关依赖

  1. if(System.getSecurityManager() != null)
  2. {
  3. AccessController.doPrivileged((PrivilegedAction < Object > )() - >
  4. {
  5. invokeAwareMethods(beanName, bean);
  6. return null;
  7. }, getAccessControlContext());
  8. }
  9. else
  10. {
  11. invokeAwareMethods(beanName, bean);
  12. } //
  13. 4. BeanPostProcessor 前置处理 Object wrappedBean = bean;
  14. if(mbd == null || !mbd.isSynthetic())
  15. {
  16. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  17. } //
  18. 5. 若实现 InitializingBean 接口, 调用 afterPropertiesSet() 方法 //
  19. 6. 若配置自定义的 init - method方法, 则执行
  20. try
  21. {
  22. invokeInitMethods(beanName, wrappedBean, mbd);
  23. }
  24. catch(Throwable ex)
  25. {
  26. throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex);
  27. } //
  28. 7. BeanPostProceesor 后置处理
  29. if(mbd == null || !mbd.isSynthetic())
  30. {
  31. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  32. }
  33. return wrappedBean;
  34. }


在 invokInitMethods() 方法中会检查 InitializingBean 接口和 init-method 方法,销毁的过程也与其类似:

  1. // DisposableBeanAdapter.java public void destroy() { //
  2. 9. 若实现 DisposableBean 接口, 则执行 destory() 方法
  3. if(this.invokeDisposableBean)
  4. {
  5. try
  6. {
  7. if(System.getSecurityManager() != null)
  8. {
  9. AccessController.doPrivileged((PrivilegedExceptionAction < Object > )() - >
  10. {
  11. ((DisposableBean) this.bean).destroy();
  12. return null;
  13. }, this.acc);
  14. }
  15. else
  16. {
  17. ((DisposableBean) this.bean).destroy();
  18. }
  19. }
  20. } //
  21. 10. 若配置自定义的 detory - method 方法, 则执行
  22. if(this.destroyMethod != null)
  23. {
  24. invokeCustomDestroyMethod(this.destroyMethod);
  25. }
  26. else if(this.destroyMethodName != null)
  27. {
  28. Method methodToInvoke = determineDestroyMethod(this.destroyMethodName);
  29. if(methodToInvoke != null)
  30. {
  31. invokeCustomDestroyMethod(ClassUtils.getInterfaceMethodIfPossible(methodToInvoke));
  32. }
  33. }
  34. }


从 Spring 的源码我们可以直观的看到其执行过程,而我们记忆其过程便可以从这 4 个阶段出发,实例化、属性赋值、初始化、销毁。其中细节较多的便是初始化,涉及了 Aware、BeanPostProcessor、InitializingBean、init-method 的概念。这些都是 Spring 提供的扩展点,其具体作用将在下一节讲述。
3. 扩展点的作用
3.1 Aware 接口
若 Spring 检测到 bean 实现了 Aware 接口,则会为其注入相应的依赖。所以通过让bean 实现 Aware 接口,则能在 bean 中获得相应的 Spring 容器资源
Spring 中提供的 Aware 接口有:

  1. BeanNameAware:注入当前 bean 对应 beanName;
  2. BeanClassLoaderAware:注入加载当前 bean 的 ClassLoader;
  3. BeanFactoryAware:注入 当前BeanFactory容器 的引用。

其代码实现如下:

  1. // AbstractAutowireCapableBeanFactory.java private void invokeAwareMethods(final String beanName, final Object bean)
  2. {
  3. if(bean instanceof Aware)
  4. {
  5. if(bean instanceof BeanNameAware)
  6. {
  7. ((BeanNameAware) bean).setBeanName(beanName);
  8. }
  9. if(bean instanceof BeanClassLoaderAware)
  10. {
  11. ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
  12. }
  13. if(bean instanceof BeanFactoryAware)
  14. {
  15. ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
  16. }
  17. }
  18. }


以上是针对 BeanFactory 类型的容器,而对于 ApplicationContext 类型的容器,也提供了 Aware 接口,只不过这些 Aware 接口的注入实现,是通过 BeanPostProcessor 的方式注入的,但其作用仍是注入依赖。

  1. EnvironmentAware:注入 Enviroment,一般用于获取配置属性;
  2. EmbeddedValueResolverAware:注入 EmbeddedValueResolver(Spring EL解析器),一般用于参数解析;
  3. ApplicationContextAware(ResourceLoader、ApplicationEventPublisherAware、MessageSourceAware):注入 ApplicationContext 容器本身。

其代码实现如下:

  1. // ApplicationContextAwareProcessor.java private void invokeAwareInterfaces(Object bean)
  2. {
  3. if(bean instanceof EnvironmentAware)
  4. {
  5. ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
  6. }
  7. if(bean instanceof EmbeddedValueResolverAware)
  8. {
  9. ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
  10. }
  11. if(bean instanceof ResourceLoaderAware)
  12. {
  13. ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
  14. }
  15. if(bean instanceof ApplicationEventPublisherAware)
  16. {
  17. ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
  18. }
  19. if(bean instanceof MessageSourceAware)
  20. {
  21. ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
  22. }
  23. if(bean instanceof ApplicationContextAware)
  24. {
  25. ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
  26. }
  27. }


3.2 BeanPostProcessor
BeanPostProcessor 是 Spring 为修改 bean提供的强大扩展点,其可作用于容器中所有 bean,其定义如下:
public interface BeanPostProcessor { // 初始化前置处理 default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } // 初始化后置处理 default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } } 复制代码
常用场景有:

  1. 对于标记接口的实现类,进行自定义处理。例如3.1节中所说的ApplicationContextAwareProcessor,为其注入相应依赖;再举个例子,自定义对实现解密接口的类,将对其属性进行解密处理;
  2. 为当前对象提供代理实现。例如 Spring AOP 功能,生成对象的代理类,然后返回。
  1. // AbstractAutoProxyCreator.java public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName)
  2. {
  3. TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
  4. if(targetSource != null)
  5. {
  6. if(StringUtils.hasLength(beanName))
  7. {
  8. this.targetSourcedBeans.add(beanName);
  9. }
  10. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
  11. Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
  12. this.proxyTypes.put(cacheKey, proxy.getClass()); // 返回代理类 return proxy; } return null; }


3.3 InitializingBean 和 init-method
InitializingBean 和 init-method 是 Spring 为 bean 初始化提供的扩展点。
InitializingBean接口 的定义如下:
public interface InitializingBean { void afterPropertiesSet() throws Exception; } 复制代码
在 afterPropertiesSet() 方法写初始化逻辑。
指定 init-method 方法,指定初始化方法:


<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="demo" class="com.chaycao.Demo" init-method="init()"/> </beans> 复制代码
DisposableBean 和 destory-method 与上述类似,就不描述了。


4. 总结
最后总结下如何记忆 Spring Bean 的生命周期:

  • 首先是实例化、属性赋值、初始化、销毁这 4 个大阶段;
  • 再是初始化的具体操作,有 Aware 接口的依赖注入、BeanPostProcessor 在初始化前后的处理以及 InitializingBean 和 init-method 的初始化操作;
  • 销毁的具体操作,有注册相关销毁回调接口,最后通过DisposableBean 和 destory-method 进行销毁。
posted @ 2021-03-23 20:24  nuoxin  阅读(121)  评论(0)    收藏  举报