Programming

Performing action when web application is starting and shutting down

There are at least three ways to perform actions when a web application is starting and shutting down:

Using ServletContextListener from the Servlet API #

Keeping things simple, you can implement ServletContextListener:

@WebListener
public class StartupListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Perform action during application's startup
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // Perform action during application's shutdown
    }
}

Using @ApplicationScoped and @Observes from CDI #

If you have CDI enabled, you can use an @ApplicationScoped-bean and @Observes for hooking your code to application events:

@ApplicationScoped
public class StartupListener {

    public void init(@Observes
                     @Initialized(ApplicationScoped.class) ServletContext context) {
        // Perform action during application's startup
    }

    public void destroy(@Observes
                        @Destroyed(ApplicationScoped.class) ServletContext context) {
        // Perform action during application's shutdown
    }
}

Please bear in mind you must use @ApplicationScoped from the javax.enterprise.context package and not @ApplicationScoped from the javax.faces.bean package.

Using @Startup and @Singleton from EJB #

If you rely on EJB, then you can use @Startup and @Singleton, as follows:

@Startup
@Singleton
public class StartupListener {

    @PostConstruct
    public void init() {
        // Perform action during application's startup
    }

    @PreDestroy
    public void destroy() {
        // Perform action during application's shutdown
    }
}