初始化回调

实现InitializingBean接口

org.springframework.beans.factory.InitializingBean在容器为 bean 设置所有必要的属性后,该接口让 bean 执行初始化工作。该InitializingBean接口指定了一个方法:

1
void afterPropertiesSet() throws Exception;
1
2
3
4
5
6
7
public class ExampleBean implements InitializingBean {

@Override
public void afterPropertiesSet() {
// do some initialization work
}
}

建议不要使用该InitializingBean接口,因为它使得代码耦合到 Spring。

JSR-250注解

建议使用@PostConstruct注释或指定 POJO 初始化方法。

将其在代码中指定的初始化方法上添加注解即可

1
2
3
4
5
6
7
public class ExampleBean {

@PostConstruct
public void init() {
// do some initialization work
}
}

基于xml

对于基于 XML 的配置元数据,您可以使用该init-method属性来指定具有 void 无参数签名的方法的名称。

1
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

配置类

在Java配置类中,你可以使用initMethod的属性

1
2
3
4
5
6
7
public class ExampleBeans {

@Bean(initMethod = "")
public ExampleBean bean() {
// define bean
}
}

后面的例子没有将代码耦合到Spring

销毁回调

实现DisposableBean接口

实现该org.springframework.beans.factory.DisposableBean接口可以让 bean 在包含它的容器被销毁时获得回调。该 DisposableBean接口指定了一个方法:

1
void destroy() throws Exception;

我们建议您不要使用DisposableBean回调接口,因为它不必要地将代码耦合到 Spring。

1
2
3
4
5
6
7
public class ExampleBean implements DisposableBean {

@Override
public void destroy() {
// do some destruction work (like releasing pooled connections)
}
}

JSR-250注解

使用@PreDestroy注释或指定 bean 定义支持的泛型方法。

1
2
3
4
5
6
7
public class ExampleBean {

@PreDestroy
public void destroy() {
// do some destruction work (like releasing pooled connections)
}
}

基于xml

使用基于XML的配置元数据时,您可以使用destroy-method该属性<bean/>。随着Java的配置,你可以使用destroyMethod的属性@Bean

1
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>

配置类

在配置类中,指定destroyMethod即可

1
2
3
4
5
6
7
public class ExampleBeans {

@Bean(destroyMethod = "")
public ExampleBean bean() {
// define bean
}
}

默认初始化和销毁方法

1
2
3
4
5
6
7
<beans default-init-method="init">

<bean id="blogService" class="com.something.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>

</beans>

只需要在<beans>标签上指定default-init-methoddefault-destroy-method,spring就会在装配bean时查找每个bean是否存在同名方法,有则调用。

如果bean的命名约定不同,也可以在<bean>指定自身的init-methoddestroy-method属性来覆盖默认方法

总结

从 Spring 2.5 开始,您可以通过三个选项来控制 bean 生命周期行为:

  • InitializingBeanDisposableBean回调接口
  • 自定义init()destroy()方法
  • @PostConstruct@PreDestroy 注解。您可以组合这些机制来控制给定的 bean。

为同一个 bean 配置的多个生命周期机制,具有不同的初始化方法,调用如下:

  1. 带有注释的方法 @PostConstruct
  2. afterPropertiesSet()InitializingBean回调接口定义
  3. 自定义配置init()方法

销毁方法以相同的顺序调用:

  1. 带有注释的方法 @PreDestroy
  2. destroy()DisposableBean回调接口定义
  3. 自定义配置destroy()方法