spring的init-method和destroy-method方法使用

本文详细介绍了Spring框架中Bean的生命周期管理,特别是初始化和销毁回调方法的配置方式。通过实例展示了如何为Bean指定初始化方法和销毁方法,确保资源的正确释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[url]http://static.springsource.org/spring/docs/2.0.x/reference/beans.html[/url]
3.5.1.2. Destruction callbacks
<bean id="datasource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="$[]" />
</bean>
destroy-method指定了当要销毁bean datasource之前要做的操作,也就是这个bean的收尾工作。
这里是指定了close()方法。
Closes and releases all idle connections that are currently stored in the connection pool associated with this data source.
http://commons.apache.org/dbcp/apidocs/org/apache/commons/dbcp/BasicDataSource.html
也可以像下面这样设置全局的init方法
<beans default-init-method="init">
<bean id="blogService" class="com.foo.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>
</beans>

要注意的是init和interceptor一起使用的情况,当bean和intereptor分开定义时,可以绕过proxy访问这个bean了。但是,还是不要在init里关联interceptor,因为
这样bean的生命周期会与proxy/interceptors耦合:
Finally, please be aware that the Spring container guarantees that a configured initialization callback is called immediately after a bean has been supplied with all of it's dependencies. This means that the initialization callback will be called on the raw bean reference, which means that any AOP interceptors or suchlike that will ultimately be applied to the bean will not yet be in place. A target bean is fully created first, then an AOP proxy (for example) with its interceptor chain is applied. Note that, if the target bean and the proxy are defined separately, your code can even interact to the raw target bean, bypassing the proxy. Hence, it would be very inconsistent to apply the interceptors to the init method, since that would couple the lifecycle of the target bean with its proxy/interceptors, and leave strange semantics when talking to the raw target bean directly.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值