Spring中Bean的生命周期(归纳总结,全程干货)

10 阅读3分钟

Bean生命周期是什么?

控制反转,就是把new对象的权利交给Spring容器,所有的对象都被容器控制。被Spring控制的对象就叫做Bean。由于Spring容器控制Bean,所以在Spring容器中,Bean会有一个从出生到死亡的生命周期。

Bean生命周期阶段

Bean生命周期大致分为以下几个阶段: image.png

Bean生命周期各阶段间的回调

1. 实例化前后:
InstantiationAwareBeanPostProcessor接口提供了三个方法用于实例化前后的方法回调。

  • postProcessBeforeInstantiation方法,用于实例化前的回调,可以对即将实例化的类进行干预或替换实例化行为或执行一些特殊的逻辑;
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
   return null;
}
  • postProcessAfterInstantiation方法,用于实例化后、属性赋值前的回调,可以决定是否对已经实例化的Bean进行属性赋值(返回true进行属性赋值,返回false中断并跳过属性赋值);
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
   return true;
}
  • postProcessProperties方法,用于属性赋值前的回调,可以自定义修改已经实例化的Bean要填充的属性;
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName
      throws BeansException {

   return pvs;
}

2. Aware相关接口
Aware相关接口的回调是在属性赋值后初始化前,有很多接口,例如:

image.png 3. 初始化前后:
BeanPostProcessor接口提供了两个方法用于初始化前后的方法回调。

  • postProcessBeforeInitialization方法,用于 Bean 的属性赋值之后但在初始化之前调用,对 Bean 进行额外的预处理操作,例如修改属性、日志记录、添加代理;
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
   return bean;
}
  • postProcessAfterInitialization方法,用于 Bean 的初始化方法成功执行之后调用,例如进一步修改 Bean 的状态、增加额外的功能包装(如代理)、或者对 Bean 进行某种形式的装饰或增强;
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
   return bean;
}

Bean生命周期各阶段中的回调

1. 初始化中:
有三种方式用于初始化的方法回调。

  • InitializingBean接口,提供了afterPropertiesSet方法,用于在属性赋值后调用;
public interface InitializingBean {

   /**
    * Invoked by the containing {@code BeanFactory} after it has set all bean properties
    * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
    * <p>This method allows the bean instance to perform validation of its overall
    * configuration and final initialization when all bean properties have been set.
    * @throws Exception in the event of misconfiguration (such as failure to set an
    * essential property) or if initialization fails for any other reason
    */
   void afterPropertiesSet() throws Exception;

}
  • @PostConstruct注解,在属性赋值后,带有该注解的方法会被自动调用;
@Component
public class MyAnnotatedBean {
4    // ...
5
6    @PostConstruct
7    public void preDestroyMethod() {
8        // 在此处执行初始化Bean所需的工作
9    }
10}
  • XML配置中的init-method属性,在属性赋值后,指定的方法会被自动调用;
<bean id="myBean" class="com.example.MyBean" init-method="initialBean"/>

2. 销毁中:
有三种方式用于销毁的方法回调。

  • DisposableBean接口,提供了destroy方法,用于在Spring容器关闭当前Bean销毁前的回调,一般用于进行资源清理;
public interface DisposableBean {

   /**
    * Invoked by the containing {@code BeanFactory} on destruction of a bean.
    * @throws Exception in case of shutdown errors. Exceptions will get logged
    * but not rethrown to allow other beans to release their resources as well.
    */
   void destroy() throws Exception;

}
  • @PreDestroy,当Spring容器关闭当前Bean销毁前,带有该注解的方法会被自动调用;
@Component
public class MyAnnotatedBean {
4    // ...
5
6    @PreDestroy
7    public void preDestroyMethod() {
8        // 在此处执行销毁Bean所需的清理工作
9    }
10}
  • XML配置中的destroy-method属性,当Spring容器关闭当前Bean销毁前,指定的方法会被自动调用;
<bean id="myBean" class="com.example.MyBean" destroy-method="cleanup"/>

Bean生命周期流程总览

image.png