Bean的生命周期回调
Bean的生命周期回调主要是在Bean对象创建和销毁的过程中会执行一些init和destroy方法,了解不同形式的init和destroy声明方法,以及它们之间的先后执行顺序会有助于我们理解Bean的生命周期过程。下文主要介绍了生命周期回调的各种使用方式,以及在Spring中是如何实现的。
常用的三种形式:
InitializingBean和DisposableBean接口,分别实现afterPropertiesSet和destroy方法;- JSR-250下的
@PostConstruct和@PreDestroy注解; - 在Spring xml文件中声明
init-method和destroy-method属性。
不推荐使用InitializingBean、DisposableBean接口,因为可能会导致和Spring高耦和。
多种形式共同作用于一个Bean时,按照如下顺序执行:
- @PostConstruct注解指定的方法;
- InitializingBean接口实现的afterPropertiesSet()方法;
- init-method属性指定的方法;
- @PreDestroy注解指定的方法;
- DisposableBean接口实现的destroy方法;
- destroy-method属性指定的方法。
示例:
public class X implements InitializingBean, DisposableBean {
@PostConstruct
public void postConstruct() {
System.out.println("PostConstruct.....");
}
public X() {
System.out.println("X construct...");
}
@PreDestroy
public void preDestroy() {
System.out.println("PreDestroy.....");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet...");
}
@Override
public void destroy() throws Exception {
System.out.println("destroy...");
}
public void init() {
System.out.println("init...");
}
public void destroyMethod() {
System.out.println("destroyMethod...");

本文详细阐述了Spring中Bean的生命周期回调,包括init和destroy方法的不同形式,如接口、注解以及XML配置,并讨论了它们的执行顺序。推荐使用@PostConstruct和@PreDestroy注解,避免与Spring高耦合。示例展示了Bean从创建到销毁的过程,包括属性注入、初始化和销毁的方法调用顺序。
最低0.47元/天 解锁文章
1437

被折叠的 条评论
为什么被折叠?



