考虑这个例子
@Component
class MyExpensiveClass {
private DB db;
}
何时 Spring
应用程序实例化一个bean myExpensiveClass
已创建。
现在,如果我要关闭 applicationContext,我想释放 db
的句柄。 .
有什么方法可以在 Spring 中做到这一点吗?就像实现一个方法和 Spring
称之为?
最佳答案
如果使用xml配置,可以注册一个init和destroy方法
<bean id="customerService"class="com.mkyong.customer.services.CustomerService"
init-method="initIt" destroy-method="cleanUp">
如果您仅使用注释
@Configuration
public class AppConfig {
@Bean(initMethodName="init")
public Foo foo() {
return new Foo();
}
@Bean(destroyMethodName="cleanup")
public Bar bar() {
return new Bar();
}
}
关于java - Spring bean中如何释放资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34233510/