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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:51:44  来源:igfitidea点击:

How to tie the Lifecycle for a Spring Bean to the webapps' lifecycle?

javaspringtomcatjetty

提问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()方法@PostConstructstop()方法@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 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 初始化。