我想知道:Spring 配置bean需不需要加init-method和destroy-method?加和不加有什么区别?

spring可以管理容器中bean的生命周期,那为什么要对bean进行管理呢?... spring可以管理容器中bean的生命周期,那为什么要对bean进行管理呢? 展开
 我来答
test19375

推荐于2016-04-22 · TA获得超过1527个赞
知道小有建树答主
回答量:1969
采纳率:45%
帮助的人:377万
展开全部
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.

<bean id="userService" class="com.bjsxt.service.UserService" autowire="byName" init-method="init" destroy-method="destory">
<property name="userDAO" ref="userDAO"/>
</bean>
这里的init-method 表示UserService 在初始化的时候自动执行 init()方法 在销毁的时候自动执行 destory()方法
public class UserService {
private UserDAO userDAO;
public void init() {
System.out.println("init");
}
public void destory() {
System.out.println("destory");
}
public void add(User user) {
userDAO.save(user);
}
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式