如何将Spring Bean的生命周期与webapps的生命周期联系起来? [英] How to tie the Lifecycle for a Spring Bean to the webapps' lifecycle?

查看:213
本文介绍了如何将Spring Bean的生命周期与webapps的生命周期联系起来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有 start() stop()方法的bean。
当webapp的上下文处于活动状态时,在Spring的运行时启动期间会调用 start()。取消部署或停止webapp时,将调用 stop()方法。

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()方法 @PostConstruct stop()使用 @PreDestroy 的方法?

Is this correct: I annotate my start() method with @PostConstruct and the stop() method with @PreDestroy ?

通常在servlet世界中,我编写了一个ServletContextListener。
我能从ServletContextListener访问ApplicationContext吗?

Normally in the servlet world, I write a ServletContextListener. Would I be able to access the ApplicationContext from the ServletContextListener ?

推荐答案

您可以注释 start() stop()您描述的方法,或者您可以告诉Spring明确调用它们,例如

You can either annotate your start() and stop() methods as you describe, or you can tell Spring to invoke them explicitly, e.g.

<bean class="MyClass" init-method="start" destroy-method="stop"/>

至于 ServletContextListener ,它不会可以轻松访问Spring上下文。最好使用Spring自己的生命周期来进行bean初始化。

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.

这篇关于如何将Spring Bean的生命周期与webapps的生命周期联系起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆