如何将Spring Bean的生命周期与webapps的生命周期联系起来?

Jac*_*ine 4 java spring tomcat jetty

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

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

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

ska*_*man 8

您可以在描述时注释您的方法start()stop()方法,也可以告诉Spring显式调用它们,例如

<bean class="MyClass" init-method="start" destroy-method="stop"/>
Run Code Online (Sandbox Code Playgroud)

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