There are multiple ways to achieve it, depending on what you have available in your application:
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
}
}
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.
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.