Bean的生命周期
理解Bean生命周期对于掌握Spring框架至关重要,它定义了Bean从创建到销毁的完整过程。
生命周期四个阶段
Java
实例化 → 属性赋值 → 初始化 → 销毁
完整生命周期流程
Java
1. 实例化 Bean
↓
2. 属性赋值(依赖注入)
↓
3. 处理 Aware 接口
- BeanNameAware
- BeanFactoryAware
- ApplicationContextAware
↓
4. BeanPostProcessor.postProcessBeforeInitialization()
↓
5. 初始化方法
- @PostConstruct
- InitializingBean.afterPropertiesSet()
- init-method
↓
6. BeanPostProcessor.postProcessAfterInitialization()
↓
7. Bean 就绪,可使用
↓
8. 销毁方法
- @PreDestroy
- DisposableBean.destroy()
- destroy-method
代码示例
定义Bean
XML
@Component
public class LifecycleBean implements BeanNameAware, InitializingBean, DisposableBean {
private String beanName;
// 1. 实例化(构造器)
public LifecycleBean() {
System.out.println("1. 构造器执行");
}
// 2. 属性赋值(依赖注入)
@Autowired
public void setOtherBean(OtherBean otherBean) {
System.out.println("2. 属性赋值");
}
// 3. BeanNameAware回调
@Override
public void setBeanName(String name) {
this.beanName = name;
System.out.println("3. BeanNameAware: " + name);
}
// 4. @PostConstruct初始化
@PostConstruct
public void init() {
System.out.println("4. @PostConstruct初始化");
}
// 5. InitializingBean回调
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("5. InitializingBean.afterPropertiesSet()");
}
// 6. 自定义init-method
public void customInit() {
System.out.println("6. customInit()");
}
// 7. @PreDestroy销毁
@PreDestroy
public void preDestroy() {
System.out.println("7. @PreDestroy销毁");
}
// 8. DisposableBean回调
@Override
public void destroy() throws Exception {
System.out.println("8. DisposableBean.destroy()");
}
// 9. 自定义destroy-method
public void customDestroy() {
System.out.println("9. customDestroy()");
}
}
BeanPostProcessor
text
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
System.out.println("BeanPostProcessor前置处理: " + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
System.out.println("BeanPostProcessor后置处理: " + beanName);
return bean;
}
}
初始化方法对比
| 方式 | 执行顺序 | 推荐度 |
|---|---|---|
| @PostConstruct | 1 | ⭐⭐⭐⭐⭐ |
| InitializingBean.afterPropertiesSet() | 2 | ⭐⭐⭐ |
| init-method | 3 | ⭐⭐⭐⭐ |
销毁方法对比
| 方式 | 执行顺序 | 推荐度 |
|---|---|---|
| @PreDestroy | 1 | ⭐⭐⭐⭐⭐ |
| DisposableBean.destroy() | 2 | ⭐⭐⭐ |
| destroy-method | 3 | ⭐⭐⭐⭐ |
XML配置方式
text
<bean id="lifecycleBean"
class="com.example.LifecycleBean"
init-method="customInit"
destroy-method="customDestroy"/>
Aware接口说明
| 接口 | 作用 |
|---|---|
| BeanNameAware | 获取Bean名称 |
| BeanFactoryAware | 获取BeanFactory |
| ApplicationContextAware | 获取ApplicationContext |
| EnvironmentAware | 获取Environment |
| ResourceLoaderAware | 获取ResourceLoader |
要点总结
- 生命周期四阶段:实例化、属性赋值、初始化、销毁
- 初始化方法执行顺序:@PostConstruct → InitializingBean → init-method
- 销毁方法执行顺序:@PreDestroy → DisposableBean → destroy-method
- BeanPostProcessor在初始化前后执行,常用于AOP代理创建
- 推荐使用注解方式(@PostConstruct/@PreDestroy)更简洁
📝 发现内容有误?点击此处直接编辑