I have a Java EE application which should start a synchronization process with an external system once after its deployment.
How could I implement this requirement?
Below are listed a couple of popular methods for getting lifecycle callbacks in JavaEE apps.
Create a javax.servlet.ServletContextListener implementation
If you have a web component to your .ear file (embedded .war) or your deployment is a .war by itself you can add a ServletContextListener to your web.xml
and get a callback when the server starts or is shutting down.
Example:
package com.stackoverflow.question
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
public class MyServletContextListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
/* Do Startup stuff. */
}
@Override
public void contextDestroyed(ServletContextEvent contextEvent) {
/* Do Shutdown stuff. */
}
}
and then add this configuration to your web.xml
deployment descriptor.
$WAR_ROOT/WEB-INF/web.xml
.
com.stackoverflow.question.MyServletContextListener
Create an EJB 3.1 @Startup Bean
This method uses an EJB 3.1 singleton to get a startup and shutdown callback from the server.
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Startup;
import javax.ejb.Singleton;
@Singleton
@Startup
public class LifecycleBean {
@PostConstruct
public void init() {
/* Startup stuff here. */
}
@PreDestroy
public void destroy() {
/* Shutdown stuff here */
}
}