spring bean 生命周期回调
spring bean的生命周期回调有两种:初始化回调(init-method) 销毁回调(destory-method)
实现生命周期回调有三种方法:实现接口、xml配置、使用注解
初始化生命周期回调(init-method)实现:
- 实现org.springframework.beans.factory.InitializingBean接口,eg
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
2、xml配置init-method
public class ExampleBean {
public void init() {
// do some initialization work
}
}
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
3、使用注解
使用JSP-250规范中的注解@PostConstruct
public class ExampleBean {
@PostConstruct
public void customer_init() {
System.out.println("@PostConstruct注解指定的初始化方法:customer_init。" );
}
}
使用java config注解
@Bean(initMethod = "customer_init")
public User user() {
...
}
生命周期销毁回调(destory-method)
实现org.springframework.beans.factory.DisposableBean接口
public class AnotherExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work (like releasing pooled connections)
}
}
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
使用xml注解,配置destory-method元素
public class ExampleBean {
public void cleanup() {
// do some destruction work (like releasing pooled connections)
}
}
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
使用注解
JSR-250注解的方式
public class User {
@PreDestory
public void customer_destory() {
System.out.println("调用destory-method指定的初始化方法:customer_destory。" );
}
}
使用java Config,要在@Bean注解中使用initMehtod属性
@Bean( destroyMethod = "customer_destory")
public User user() {
...
}
全局设置
在顶级元素中定义初使化和销毁函数(必须统一函数名)
<beans default-init-method="customer_init" default-destroy-method="customer_destory">
<bean id="CristianoRonaldo" class="twm.spring.LifecycleTest.User" />
</beans>
总结
1、在一个bean中,配置多种生命周期回调机制,会按照下列次序调用:
带@PostConstruct注解的方法 -> InitializingBean回调接口中的afterPropertiesSet()方法 ->自定义的init()方法
2、销毁回调也使用相同的次序
带@PreDestroy注解的方法 -> DisposableBean回调接口中的destroy()方法 ->自定义的destroy()方法
3、不管是通过实现 InitializingBean/DisposableBean 接口,还是通过 <bean> 元素的init-method/destroy-method 属性进行配置,都只能为 Bean 指定一个初始化 / 销毁的方法。但是使用 @PostConstruct 和 @PreDestroy 注释却可以指定多个初始化 / 销毁方法,那些被标注 @PostConstruct 或 @PreDestroy 注释的方法都会在初始化 / 销毁时被执行。
4、不建议使用接口和注解实现方式,因为这会让pojo类与Spring框架紧耦合。