简体   繁体   中英

How can i initialiaze objects in a rest server with jersey (java)?

I have a dumb question. I have got a java web application and a rest interfaces with jersey. Where can I put a initialization block of code?

For example, I have got a singleton, with a method "createInstance". How can i execute "createInstance" method once time the rest server is running. Is there something like "Main()" to place initialization stuff?

I have got also servlets in the proyects but those are executing when a user open the webpage.

I want to know if exist any place to put my initialization code.

Finally i found the solution:

For execute initialization code i can create a implementation of "ServletContextListener".

In this way i do this:

package foopackage;

...
public class ServletContextClass implements ServletContextListener
{  

    @Override
    public void contextInitialized(ServletContextEvent arg0) 
    {        
            ...     
    }


    @Override
    public void contextDestroyed(ServletContextEvent arg0) 
    {
           ...
    }
}

To use this listener after the application server initialization it is necessary to put this in the web.xml.

 <listener>
     <listener-class>foopackage.ServletContextClass</listener- class>
 </listener>

It is not at all clear what you mean by "initialize objects". I guess the obvious answer is that you initialize an object wherever you need it.

If you need to create a Singleton you would create it as you would do with any other singleton in Java, using a static filed or an enum; and you would get an instance of it inside the one of your REST methods. For instance

@GET
@Produces("application/xml")
public String getData() {
   Singleton singleton = Singleton.getInstance();
   String result = singleton.domSomething();
   return result;
}

If what you want is to make your resource (web service) a singleton, then you can do so by extending javax.ws.rs.core.Application and then, depending on the JAX-RS implementation and server that you are using, you may need to configure your web.xml to initialize your REST services using this Application definition. This class has method named getSingletons() that you can extend to provide singletons of your resources.

Rest resource is just like any other class.
You can use the constructor to initialize your objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM