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

spring可以管理容器中bean的生命周期,那为什么要对bean进行管理呢?

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;
}
}
温馨提示:答案为网友推荐,仅供参考