Question

I'd like to know what the expected lifecycle behavior is for a class that responds to REST requests.

I have a class that's derived from javax.ws.rs.core.Application that identifies another class for responding to requests.

In that other class, it is annotated with @Path("foo") and methods within this class are annotated with @Path("bar"). When a request is made to foo/bar, I can see that the constructor is executed, then the PostConstruct method is properly called. After the method returns a response to the client, I can see that PreDestroy is called and then the class is squashed. On the next request, the process repeats.

Is this the correct behavior? Or is there a way that this class can remain in memory so that it doesn't need to go through the constructor and PostConstruct each time a request is made? This method relies on JAXB marshalling and various XSL transformations - I would like to cache the compiled XSLT transformation objects as well as the results of some transformations, but if the class is reinstantiated each time it is called, it makes it impossible for local caching.

This is running with Java 7, Wink, and Tomcat 7. Can someone please let me know if this is the expected behavior, or am I missing something that will just keep this class alive?

Thanks.

Was it helpful?

Solution

By JAX-RS specification, the Resources (the classes annotated with @Path) are created per request.

There are several ways to override this behavior.

The simplest way that can be used according to the JAX-RS specification, is to create a resource instance yourself (you are responsible to call the PostConstruct, not sure when and how you call to PostDestroy in this case) and return it using javax.ws.rs.core.Application.getSingletons()

Alternately, you can put @org.apache.wink.common.annotations.Scope(ScopeType.SINGLETON) annotation on your resource.

If you use Spring, Wink has a neat Spring integration module, so the Spring's lifecycle will be used. See http://incubator.apache.org/wink/1.0/html/5.5%20Spring%20Integration.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top