有时想让 Spring Bean 在创建或者销毁时执行某些特定方法,有三种方式
- 使用注解
@PostConstruct
和@PreDestroy
- 实现
InitializingBean
和DisposableBean
- XML 配置中指定 init-method 和 destroy-method
Spring 官方推荐第一种方式,使用注解 @PostConstruct
和 @PreDestroy
,这减少了对 Spring 框架的依赖,因为这是 Java 提供的注解,只需将这两个注解标在你想要回调的方法上
public class Example {
@PostConstruct
public void init() {
// init
}
@PreDestroy
public void destroy() {
// destroy
}
}
第二种方式需要实现 InitializingBean
和 DisposableBean
接口,分别实现 afterPropertiesSet()
和 destroy()
方法
public class Example implements InitializingBean, DisposableBean {
public void afterPropertiesSet() {
// do some initialization work
}
public void destroy() {
// do some destruction work
}
}
第三种方式需要使用 XML 配置
<bean id="exampleBean" class="examples.ExampleBean" init-method="init" destroy-method="destroy"/>