Hi I am using Rest service with JAX-RS in java. I want a piece of code that should be executed only once when application is started. That code should not be executed on each request. How can I do that?
@Path("/xyz")
class RestService{
//do anything here will be executed on each request.
}
I am using tomcat server. Any help would be very appreciative.
This is the exact use case for a context listener. Please see this article for a good example of a servlet context listener. The article shows how to define your listener and how to wire it into your web application.
You can write the following class where you register your resources. In the constructor of your class you can call any initialization code that you want and pass that content to the constructor of each of the resources that you register.
If you want to have initialization code that is different for each resource, then you could do that in the constructor of your resources. In this example below I am initializing Hibernate configurations and passing it to the resources
@ApplicationPath("/")
public class AppNameApplication extends Application{
private Set<Object> singletons=new HashSet<Object>();
private Set<Class<?>> empty=new HashSet<Class<?>>();
private final SessionFactory sessionFactory;
public AppNameApplication(){
try{
Configuration configuration=new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
this.sessionFactory=configuration.buildSessionFactory(serviceRegistry);
}
catch(Throwable ex){
System.err.println("Initial SessionFactory creation failed."+ ex);
throw new ExceptionInInitializerError(ex);
}
singletons.add(new Resource1(sessionFactory));
singletons.add(new Resource2(sessionFactory));
singletons.add(new Resource3(sessionFactory));
}
@Override
public Set<Class<?>> getClasses(){
return empty;
}
@Override
public Set<Object> getSingletons(){
return singletons;
}
}
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