Marco Rehmer
Marco Rehmer

Reputation: 1093

init method in jersey jax-rs web service

I'm new with jax-rs and have build a web service with jersey and glassfish.

What I need is a method, which is called once the service is started. In this method I want to load a custom config file, set some properties, write a log, and so on ...

I tried to use the constructor of the servlet but the constructor is called every time a GET or POST method is called.

what options I have to realize that?

Please tell, if some dependencies are needed, give me an idea how to add it to the pom.xml (or else)

Upvotes: 8

Views: 4445

Answers (1)

cassiomolin
cassiomolin

Reputation: 130857

There are multiple ways to achieve it, depending on what you have available in your application:

Using ServletContextListener from the Servlet API

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

In this approach, 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
    }
}

If you are interested in reading a properties file, check this question. If you are using CDI and you are open to add Apache DeltaSpike dependencies to your project, considering having a look at this answer.

Upvotes: 12

Related Questions