你好,我正在使用Java中的JAX-RS Rest服务。我想要一段代码,在应用程序启动时只执行一次。该代码不应在每个请求上执行。我该如何做?
@Path("/xyz")
class RestService{
//do anything here will be executed on each request.
}
我正在使用Tomcat服务器。非常感谢您的帮助。
你好,我正在使用Java中的JAX-RS Rest服务。我想要一段代码,在应用程序启动时只执行一次。该代码不应在每个请求上执行。我该如何做?
@Path("/xyz")
class RestService{
//do anything here will be executed on each request.
}
@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;
}
}