Search code examples
jakarta-eejax-rs

Perform action when JAX-RS/Java EE application is starting


Is there some way to check when a JAX-RS/Java EE application is starting/deployed?

At these moment, I'd like to check whether a database is initialized. Otherwise, only if the database is not initialized, I need to initialize it, and I need to check it when the Java EE application starts.

So, I need to know if there is any way to catch when a JAX-RS/Java EE application starts.

Any ideas?


Solution

  • There are at least three ways to achieve it:

    Using ServletContextListener from the Servlet API

    Since JAX-RS is built on the top of the Servlet API, the following piece of 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

    When using JAX-RS with CDI, you can have the following:

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

    When using JAX-RS with EJB, you can try:

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