java 如何将 Spring Bean 的生命周期与 webapps 的生命周期联系起来?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1762246/
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
How to tie the Lifecycle for a Spring Bean to the webapps' lifecycle?
提问by Jacques René Mesrine
I want to create a bean that has start()and stop()methods.
When the webapp's context is active, start()is called during Spring's runtime bootup. When the webapp is undeployed or stopped, the stop()method is invoked.
我想创建一个具有start()和stop()方法的 bean 。当 webapp 的上下文处于活动状态时,start()在 Spring 的运行时启动期间调用。当 webapp 被取消部署或停止时,该stop()方法被调用。
Is this correct: I annotate my start()method with @PostConstructand the stop()method with @PreDestroy?
这是正确的:我用 注释我的start()方法@PostConstruct和stop()方法@PreDestroy?
Normally in the servlet world, I write a ServletContextListener. Would I be able to access the ApplicationContext from the ServletContextListener ?
通常在 servlet 世界中,我编写了一个 ServletContextListener。我能从 ServletContextListener 访问 ApplicationContext 吗?
回答by Eero
Implement the Lifecycleor SmartLifecycleinterfaces in your bean, as described in
在 bean 中实现Lifecycle或SmartLifecycle接口,如
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
Your ApplicationContextwill then cascade its start and stop events to all Lifecycle implementations. See also the JavaDocs:
然后,您的ApplicationContext会将其开始和停止事件级联到所有 Lifecycle 实现。另请参阅 JavaDocs:
回答by skaffman
You can either annotate your start()and stop()methods as you describe, or you can tell Spring to invoke them explicitly, e.g.
您可以按照您的描述注释您的start()和stop()方法,也可以告诉 Spring 显式调用它们,例如
<bean class="MyClass" init-method="start" destroy-method="stop"/>
As for the ServletContextListener, it would not have easy access to the Spring context. It's best to use Spring's own lifecycle to do your bean initialization.
至于ServletContextListener,它无法轻松访问 Spring 上下文。最好使用 Spring 自己的生命周期来进行 bean 初始化。

