深入解读Spring Framework IoC容器(第八弹:Bean的初始化和销毁)

初始化回调函数

org.springframework.beans.factory.InitializingBean接口,可以让容器在设置好bean的所有必要属性后,执行初始化。InitializingBean接口仅指定了一个方法:void afterPropertiesSet() throws Exception;如:

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {

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

}

不过我们一般不使用InitializingBean接口,因为这样会将代码和Spring耦合起来。推荐使用@PostConstruct注解或者指定一个POJO的初始化方法。在XML配置里,使用init-method属性去指定方法名,并且该方法无参数签名。 例如:

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

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

}

析构回调函数

org.springframework.beans.factory.DisposableBean接口,可以让容器在销毁bean时回调。 DisposableBean接口也只定义了一个方法:void destroy() throws Exception;如:

<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {

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

}

一般我们不使用DisposableBean接口,因为会与Spring耦合。建议使用@PreDestroy注解或者指定一个普通的方法,但能由bean定义支持。使用destroy-method属性。例如:

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

    public void cleanup() {
        // do some destruction work (like releasing pooled connections)
    }

}

缺省的初始化和析构方法

像上面那样,在XML配置里使用init-method和destroy-method虽然不会和Spring耦合,但是如果每个bean都要这样配置也很麻烦。
我们可以在顶级的 <beans/>元素中使用default-init-method属性。这个属性的含义是 Spring IOC容器在bean创建和装配的时候会将 init方法作为实例化回调方法。如果类有这个方法,则会在适当的时候执行。

<beans default-init-method="init">
</beans>

销毁回调方法也一样,在顶级的<beans/>元素中使用 default-destroy-method 属性。

最后要注意,Spring容器保证在bean的所有依赖都满足后立即执行配置的初始化回调。就是说初始化回调在原生bean上调用,这个时候任何诸如AOP拦截器之类的将不能被应用。

组合生命周期机制

从上面我们知道了,有三种控制bean生命周期行为的方式:
- InitializingBean和DisposableBean回调接口;
- 在XML配置里使用init-method和destroy-method配置的自定义init()和destroy()方法;
- @PostConstruct和@PreDestroy注解。

如果为同一个bean配置多个生命周期机制,不同的初始化方法,调用顺序如下:
1. @PostConstruct注解
2. InitializingBean的afterPropertiesSet()定义
3. 在XML配置里使用init-method配置的自定义init()方法

析构方法调用顺序也一样:
1. @PreDestroy注解
2. DisposableBean 的 destroy() 定义
3. 在XML配置里使用destroy-method配置的自定义destroy()方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值