How do I write code to initialize web applications in a rest service?

Hi I am using the Restore service with JAX-RS in java. I want a piece of code to be executed only once, when the application starts. This code doesn't have to be executed on every request. How can i do this?
@Path("/xyz")
class RestService{
//do anything here will be executed on each request.
}

      

I am using tomcat server. Any help would be greatly appreciated.

+3


source to share


2 answers


This is the exact use case for a context listener. Please see this article for a good example of a servlet context listener. This article shows you how to define your listener and how to connect it to your web application.



+2


source


You can write the following class where you register your resources. In the constructor of your class, you can call whatever initialization code you want and pass that content to the constructor of each of the resources you register.

If you want to have initialization code that is different for each resource, you can do this in your resource constructor. In this example below I am initializing Hibernate config and passing it to 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;
}
}

      

+1


source







All Articles