How does an JAX-RS 'endpoint' behave when

2019-03-30 03:18发布

There is something I am not sure I understand correctlty, therefore, I need help:)

I have seen this: example,

@Path("/resource")
public class Resource {
    @Context
    private HttpHeaders headers;

    @GET
    public void get(@Context UriInfo uriInfo) {
       /* use headers or uriInfo variable here */
    }
}

Does this mean that for each request the class that is transformed to 'endpoint' creates a separate thread? Because, otherwise, the headers information would not be accurate...

Can you please indicate a (short:) ) resource, not JAX-WS specifications, where I can find info about this?

1条回答
不美不萌又怎样
2楼-- · 2019-03-30 03:28

I can't think of a shorter and more direct resource than the JAX-RS 1.1 spec itself. It is clear about what you are asking:

JAX-RS provides facilities for obtaining and processing information about the application deployment context and the context of individual requests. (...)

Context is specific to a particular request (...).

May I add for completeness: that context information is obtained through the @Context annotation. As of resources, the context information is only available to the ones annotated with @Path (also called root resources). Also, @Context can inject the following context types: Application, UriInfo, HttpHeaders, Request, SecurityContext and Providers.

And about the lifecycle (request/thread management):

3.1.1 Lifecycle and Environment

By default a new resource class instance is created for each request to that resource. First the constructor is called, then any requested dependencies are injected (context is one of those dependencies), then the appropriate method 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.

The conclusion is:

  • Each request is, by default, handled by a different resource instance;
  • The context is injected at request time (thus a different context per instance).

Each specific implementation may change this lifecycle a bit, but the principles should be maintained (a context specific to each request).

As you can see, also, the spec says nothing about thread management. Since most JAX-RS implementations are Servlet-based, we can assume with certain safety that the each request instance goes to a different thread - as servlet containers are thread per request.

查看更多
登录 后发表回答