Executing task after deployment of Java EE application

后端 未结 4 1062
天命终不由人
天命终不由人 2021-02-04 04:52

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?

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 05:07

    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 */
      }
    
    }
    

提交回复
热议问题