2009-11-19 50 views
4

我想创建一个拥有start()stop()方法的bean。 当webapp的上下文处于活动状态时,在Spring的运行时启动过程中调用start()。当webapp被部署或停止时,调用stop()方法。如何将Spring Bean的生命周期与webapps的生命周期联系起来?

这是正确的:我注释我的start()方法与@PostConstructstop()方法与@PreDestroy

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

回答

8

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

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

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

10