如何将Spring Bean的生命周期绑定到Web应用程序的生命周期?

4
我想创建一个拥有start()stop()方法的Bean。当Web应用程序的上下文处于活动状态时,在Spring运行时引导期间会调用start()。在Web应用程序被卸载或停止时,将调用stop()方法。

这正确吗: 我使用@PostConstruct注释我的start()方法,使用@PreDestroy注释stop()方法?

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

2个回答

10

根据http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lifecycle-processor中的描述,在您的bean中实现LifecycleSmartLifecycle接口。

public interface Lifecycle {
  void start();
  void stop();
  boolean isRunning();
}

您的 ApplicationContext 将会对所有实现了 Lifecycle 接口的对象进行启动和停止事件的级联操作。请参阅 JavaDocs:

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/Lifecycle.html

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/context/SmartLifecycle.html


8
您可以按照您所描述的方式注释start()stop()方法,或者您可以告诉Spring显式调用它们,例如。
<bean class="MyClass" init-method="start" destroy-method="stop"/>

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接