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

本小妞迷上赌 提交于 2019-12-09 13:24:51

问题


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.

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

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


回答1:


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"/>

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.




回答2:


Implement the Lifecycle or SmartLifecycle interfaces in your bean, as described in

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lifecycle-processor

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

Your ApplicationContext will then cascade its start and stop events to all Lifecycle implementations. See also the 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



来源:https://stackoverflow.com/questions/1762246/how-to-tie-the-lifecycle-for-a-spring-bean-to-the-webapps-lifecycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!