Question

In Beginning Java EE 7 by Antonio Goncalves it is written:

In the section Writing RESTful Web Services -> Life Cycle and Callback:

Thus, the life cycle of a RESTful web service is per request so the service does not have to worry about concurrency and can use instance variables safely.

Yet a couple lines later he writes:

Remember that a RESTful web service can also be annotated with @Stateless or @Singleton to benefit from the services of session beans.

So what is it? Lifecycle per request only or can it be session too?

In addition to that, if the life cycle is session, how does it handle the @Context annotation when injecting HttpHeaders into an attribute? The headers could vary during the session, so is this attribute always updated after each request?

Was it helpful?

Solution

According to the JAX-RS specification, every implementation (like Jersey) must support the per-request behaviour:

3.1.1 Lifecycle and Environment

By default a new resource class instance is created for each request to that resource. First the constructor (see Section 3.1.2) is called, then any requested dependencies are injected (see Section 3.2), then the appropriate method (see Section 3.3) is invoked and finally the object is made available for garbage collection.

An implementation MAY offer other resource class lifecycles, mechanisms for specifying these are outside the scope of this specification. E.g. an implementation based on an inversion-of-control framework may support all of the lifecycle options provided by that framework.

This means if your Resource class is not additionally annotated, it is per-request. One well-known exception are the Spring beans: if your Rest Resource is also a Spring Bean, then Spring specifies the lifecycle of that class. The same about the EJBs (@Singleton)

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