What objects can I inject using the @Context annotation?
I'm new to JAX-RS and I'm trying to understand how the @Context
annotation is supposed to work.
At the javadoc there is a list of six classes (Application
, UriInfo
, Request
, HttpHeaders
, SecurityContext
, Providers
). However I find code on the web that use the this annotation with other types, for example:
@GET
public String something(@Context HttpServletRequest req) {
}
Is there a list of supported types that can be used with this annotations? Does this list change between implementation of the standard?
I'm currently experimenting with Jersey and I'm worried that I'll write code that cannot be ported to other JAX-RS implementation.
Solution 1:
The @Context
annotation allows you to inject request/response context details into JAX-RS provider and resource classes. Injection can be performed into a class field, a bean property or a method parameter.
The following list summarizes all the types that can be injected using the @Context
annotation, according to the JAX-RS 2.0 specification:
javax.ws.rs.core.Application
javax.ws.rs.core.HttpHeaders
javax.ws.rs.core.Request
javax.ws.rs.core.SecurityContext
javax.ws.rs.core.UriInfo
javax.ws.rs.core.Configuration
javax.ws.rs.container.ResourceContext
javax.ws.rs.ext.Providers
Except for Configuration
and Providers
, which
are injectable in both client and server-side providers, all the other types are server-side only.
The following types are available only when the application is deployed in a servlet container:
javax.servlet.HttpServletRequest
javax.servlet.HttpServletResponse
javax.servlet.ServletConfig
javax.servlet.ServletContext
JAX-RS 2.1 introduced other types that can be injected with @Context
:
javax.ws.rs.sse.Sse
javax.ws.rs.sse.SseEventSink
Besides the standard types listed above, JAX-RS implementations, such as Jersey, RESTEasy and Apache CXF, might define their own types that can be injected using @Context
.
Find below a quick description of each JAX-RS type available for injection:
Application: The instance of the application-supplied
Application
subclass can be injected into a class field or method parameter. Access to theApplication
subclass instance allows configuration information to be centralized in that class.URIs and URI templates:
UriInfo
provides both static and dynamic, per-request information, about the components of a request URI.Headers:
HttpHeaders
provides access to request header information either in map form or via strongly typed convenience methods. Response headers may be provided using theResponse
class.Content negotiation and preconditions: The methods of
Request
allow a caller to determine the best matching representation variant and to evaluate whether the current state of the resource matches any preconditions in the request.Security context: The
SecurityContext
interface provides access to information about the security context of the current request. The methods ofSecurityContext
provide access to the current user principal, information about roles assumed by the requester, whether the request arrived over a secure channel and the authentication scheme used.Providers: The
Providers
interface allows for lookup of provider instances based on a set of search criteria. This interface is expected to be primarily of interest to provider authors wishing to use other providers functionality. It is injectable in both client and server providers.Resource context: The
ResourceContext
interface provides access to instantiation and initialization of resource or subresource classes in the default per-request scope. It can be injected to help with creation and initialization, or just initialization, of instances created by an application.Configuration: Both the client and the server runtime
Configuration
s are available for injection in providers (client or server) and resource classes (server only).SSE events:
SseEventSink
represents the incoming SSE connection and provides methods to send events.Sse
provides factory methods for events and broadcasters.
This post written by Arjan Tijms suggests that future versions of JAX-RS may have a stronger integration with CDI. So @Context
may be deprecated and then removed in favor of @Inject
:
JAX-RS 2.2
For some reason, one that has largely been lost in time, JAX-RS uses its own dependency injection system based on
@Context
instead of CDI's@Inject
. While JAX-RS was updated at the last moment before its initial release to have some level of support for CDI, the fact that JAX-RS resources are not CDI beans has unnecessarily hold back the spec and has caused confusion even since JAX-RS was introduced in EE 6 (2009).This changeover to CDI could possibly happen in 2 steps; in JAX-RS 2.2 everything that can now be injected by
@Context
should also be injectable using@Inject
and JAX-RS resources would be CDI beans by default (perhaps unless explicitly disabled). At the same time@Context
would be deprecated. In JAX-RS 3.0@Context
would then be actually removed.
Solution 2:
The riveting JAX-RS specification defines all the standard types you can inject via @Context
.
But if I were you, I would just consult the specific documentation of your chosen provider to see what is available.
For example, RESTEasy provides these values via @Context
. Meanwhile, Jersey provides these. Obviously there will be overlap because of the standard context values.
Solution 3:
The @Context annotation can be used to inject 12 objects. Here is a quick summary of each of them
- HttpHeaders - HTTP header valuesand parameters
- UriInfo - URI query parameters and path variables
- SecurityContext - Gives access to security-related data for the given HTTP request
- Request - Allows precondition request processing
- ServletConfig - The ServletConfig
- ServletContext - The ServletContext
- HttpServletRequest - The HttpServletRequest instance for the request
- HttpServletResponse - The HttpServletResponse instance
- Application, Configuration, and Providers -> Provide information about the JAX-RS application, configuration and providers
- ResourceContext - Gives access to resource class instances
All of these instances can be injected in the resource method
@Path("/")
public class EndpointResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllHttpHeaders(final @Context HttpHeaders httpHeaders){
// Code here that uses httpHeaders
}
}
or as a field:
@Path("/")
public class EndpointResource {
private final @Context HttpHeaders httpHeaders;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllHttpHeaders(){
// Code here that uses httpHeaders
}
}
Here is a five part series answering the question What is @Conext used for?