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)
There are multiple ways to achieve it, depending on what you have available in your application:
ServletContextListener
from the Servlet APIOnce 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
}
}
@ApplicationScoped
and @Observes
from CDIWhen 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.
@Startup
and @Singleton
from EJBWhen 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With