我目前正在学习和试验 Spring 配置中指定的 Spring 的 init-method 和 destroy-method 属性。
我的问题是如何告诉 Spring 在程序终止之前为那些设置了该方法的 bean 调用 destroy-方法?
换句话来说,我希望在程序执行之前对所有使用 destroy-method 的 bean 执行任何拆卸操作。这可能吗?
正如许多其他人的建议,我正在阅读曼宁的书“Spring in Action”,因此我现在正在尝试这个 bean:
<bean id="auditorium" class="com.springinaction.springidol.Auditorium"
init-method="turnOnLights"
destroy-method="turnOffLights"/>
根据我的实验,Spring 不会自动执行此操作,因此,我正在使用 BeanDefinitionRegistry。然而,这涉及隐式删除 bean ,这是我想避免的。
ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
Auditorium auditorium = (Auditorium) ctx.getBean("auditorium");
// Removing the bean from container
BeanDefinitionRegistry factory = (BeanDefinitionRegistry) ctx.getAutowireCapableBeanFactory();
factory.removeBeanDefinition("auditorium");
此外,为了完整的问题,以下是我的礼堂类(class):
public class Auditorium {
private boolean isLightsOn;
public Auditorium() {
isLightsOn = false;
}
public void turnOnLights() {
isLightsOn = true;
printLights();
}
public void turnOffLights() {
isLightsOn = false;
printLights();
}
public void printLights() {
if (isLightsOn) {
System.out.println("Lights are turned on!");
} else {
System.out.println("Lights are turned off!");
}
}
}
最佳答案
当上下文为 closed 时,将调用所有 destroy
方法。或refreshed 。如果您运行独立应用程序,为了确保在应用程序结束之前调用 destroy 方法,您需要 register a shutdown hook .
所有这些方法都可以在 ConfigurableApplicationContext
接口(interface)中使用,因此您需要使用它,而不仅仅是 ApplicationContext
(几乎您要使用的任何上下文都会实现这个接口(interface),这样你就不用担心):
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
ctx.registerShutdownHook(); // this should be it, destroys are called before your app exits
在应用程序服务器等非独立(托管)场景中,关闭/刷新上下文会在关闭/重新部署时自动发生,因此您无需执行任何操作。
关于java - 如何在终止前调用容器中每个 bean 的销毁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17497393/