spring Lifecycle接口

[b]1.初始化回调[/b]
实现org.springframework.beans.factory.InitializingBean接口允许容器在设置好bean的所有必要属性后,执行初始化事宜。InitializingBean接口仅指定了一个方法:
void afterPropertiesSet() throws Exception;

通常,要避免使用InitializingBean接口(而且不鼓励使用该接口,因为这样会将代码和Spring耦合起来)可以在Bean定义中指定一个普通的初始化方法,即在XML配置文件中通过指定init-method属性来完成。如下面的定义所示:
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>

public class ExampleBean {

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

(效果)与下面完全一样
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

public class AnotherExampleBean implements InitializingBean {

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

但是没有将代码与Spring耦合在一起。
[b]析构回调[/b]
实现org.springframework.beans.factory.DisposableBean接口的bean允许在容器销毁该bean的时候获得一次回调。DisposableBean接口也只规定了一个方法:
void destroy() throws Exception;

通常,要避免使用DisposableBean标志接口(而且不鼓励使用该接口,因为这样会将代码与Spring耦合在一起)可以在bean定义中指定一个普通的析构方法,即在XML配置文件中通过指定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)
}
}

(效果)与下面完全一样
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>

public class AnotherExampleBean implements DisposableBean {

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

但是没有将代码与Spring耦合在一起。
[b]3.缺省的初始化和析构方法[/b]
如果有人没有采用Spring所指定的InitializingBean和DisposableBean回调接口来编写初始化和析构方法回调,而且团队约到使用init(), initialize(),dispose()作为生命周期回调方法的名称,有了前面的约定,就可以将Spring容器配置成在每个bean上查找事先指定好的初始化和析构回调方法名称,这样就可以简化bean定义,比如根据约定将初始化回调命名为init(),我们举例如下:
public class DefaultBlogService implements BlogService {

private BlogDao blogDao;

public void setBlogDao(BlogDao blogDao) {
this.blogDao = blogDao;
}

// this is (unsurprisingly) the initialization callback method
public void init() {
if (this.blogDao == null) {
throw new IllegalStateException("The [blogDao] property must be set.");
}
}
}

为上述类所添加的XML配置,如下所示:
<beans default-init-method="init">

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

</beans>

该属性的出现意味着Spring IoC容器会把bean上名为'init'的方法识别为初始化方法回调,并且当bean被创建和装配的时候,如果bean类具有这样的方法,它将会在适当的时候被调用,类似的,配置析构方法回调是在顶层<beans/>元素上使用'default-destroy-method'属性。使用该特性可以使你免于在每个bean上指定初始化和析构方法回调的琐碎工作,同时它很好的强化了针对初始化和析构方法回调的命名约定的一致性(一致性是一种应该时常追求的东西)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值