跳转至

Spring Bean 的生命周期

一、完整流程

实例化 → 属性填充 → Aware → BeanPostProcessor 前置 → 初始化 → BeanPostProcessor 后置 → 使用 → 销毁

二、分步

1. 实例化

调用构造函数 new 对象。

2. 属性填充

populateBean,@Autowired 注入。

3. Aware 接口

  • BeanNameAware.setBeanName
  • BeanClassLoaderAware
  • BeanFactoryAware

4. BeanPostProcessor 前置

postProcessBeforeInitialization。

5. 初始化

  • @PostConstruct
  • InitializingBean.afterPropertiesSet
  • init-method

6. BeanPostProcessor 后置

postProcessAfterInitialization。AOP 代理在这里生成。

7. 使用

Bean 就绪。

8. 销毁

  • @PreDestroy
  • DisposableBean.destroy
  • destroy-method

三、图解

构造函数
setter 注入
BeanNameAware / BeanFactoryAware
BeanPostProcessor#postProcessBeforeInitialization
@PostConstruct / afterPropertiesSet / init-method
BeanPostProcessor#postProcessAfterInitialization  ← AOP 代理
Bean 就绪
@PreDestroy / destroy

四、为什么 AOP 在后置

AOP 要代理整个 Bean,必须等 Bean 完全初始化完。所以在 postProcessAfterInitialization 里生成代理。

五、循环依赖

三级缓存就是在"实例化后、初始化前"暴露早期引用。

面试必背

实例化 → 属性填充 → 初始化 → 销毁,中间插各种 Aware 和 PostProcessor。