gpt4 book ai didi

java - 如何在终止前为容器中的每个 bean 调用销毁方法

转载 作者:行者123 更新时间:2023-12-04 04:50:39 25 4
gpt4 key购买 nike

我目前正在学习和试验 Spring 配置中指定的 Spring 的 init-method 和 destroy-method 属性。

我的问题是如何告诉 Spring 在程序终止之前为那些设置了方法的 bean 调用 destroy-method?

换句话说,我希望在程序执行之前对所有使用销毁方法的 bean 执行任何拆除操作。这甚至可能吗?

正如许多其他人所建议的那样,我正在阅读 Manning 的书“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");

此外,为了一个完整的问题,下面是我的礼堂课:
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!");
}
}
}

最佳答案

所有destroy当上下文为 closed 时调用方法或 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com