java 在 Spring 2.5 中注册关闭钩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1827212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Registering a shutdown hook in Spring 2.5
提问by Steve B.
I have a spring application which is not calling bean destroy methods on shutdown. I've seen references to this being due to instantiation in a beanRefFactory, and that this can be circumvented through manually calling registerShutdownHook() on an the application context.This method seems to have disappeared from spring between versions 2.0 - 2.5.
我有一个 spring 应用程序,它在关闭时不调用 bean destroy 方法。我已经看到对这个的引用是由于 beanRefFactory 中的实例化,这可以通过在应用程序上下文中手动调用 registerShutdownHook() 来规避。这个方法似乎从 2.0 - 2.5 版本之间的 spring 中消失了。
Can someone point me in the direction of how this is now done?
有人可以指出我现在如何完成的方向吗?
Thanks.
谢谢。
回答by sfussenegger
This method is still available in ConfigurableApplicationContextand implemented by AbstractApplicationContext.
此方法在 中仍然可用ConfigurableApplicationContext并由AbstractApplicationContext.
So you might be able to do this
所以你可能能够做到这一点
ApplicationContext ctx = ...;
if (ctx instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext)ctx).registerShutdownHook();
}
Alternatively, you could simply call ((ConfigurableApplicationContext)ctx).close()yourself while closing down the application or using your own shutdown hook:
或者,您可以((ConfigurableApplicationContext)ctx).close()在关闭应用程序或使用自己的关闭挂钩时简单地调用自己:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run(){
if (ctx instanceof ConfigurableApplicationContext) {
((ConfigurableApplicationContext)ctx).close();
}
}
});
回答by MRK187
So many upvotes, but the second statement is totally wrong, a system.exit in java would terminate the spring before ever getting to your shutdownhook, the right way to go are these 4 ways
这么多赞成票,但第二条语句是完全错误的,java 中的 system.exit 会在进入关闭钩子之前终止 spring,正确的方法是这 4 种方法
1 InitializingBean and DisposableBean callback interfaces 2 Other Aware interfaces for specific behavior 3 custom init() and destroy() methods in bean configuration file 4 @PostConstruct and @PreDestroy annotations
1 InitializingBean 和 DisposableBean 回调接口 2 特定行为的其他 Aware 接口 3 bean 配置文件中的自定义 init() 和 destroy() 方法 4 @PostConstruct 和 @PreDestroy 注释
Click here!
点击这里!

