Performing action when web application is starting and shutting down

Cassio Mazzochi Molin |

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

Using ServletContextListener from the Servlet API

The following code will do the trick:

@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, use:

@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
    }
}

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 have EJB enabled, use:

@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
    }
}