Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 338
Jacques René Mesrine Avatar asked Dec 02 '22 06:12

Jacques René Mesrine


1 Answers

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

like image 163
Eero Avatar answered Dec 21 '22 13:12

Eero