Over a million developers have joined DZone.

JAX-RS: What Is @Context?

DZone's Guide to

JAX-RS: What Is @Context?

When using JAX-RS, we often need to make use of the @Context annotation. But what exactly does it do? And what separates it from @Inject.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

The JAX-RS API from the Java EE ecosystem of technologies provides the annotation @Context, to inject 12 object instances related to the context of HTTP requests. It behaves just like the @Inject and @Autowired annotations in Java EE and Spring respectively.

The object instances that it can inject are the following:

  • SecurityContext – Security context instance for the current HTTP request
  • Request – Used for setting precondition request processing
  • Application, Configuration, and Providers -> Provide access to the JAX-RS application, configuration, and providers instances
  • ResourceContext – Resource context class instances
  • ServletConfig – The ServletConfig instance instance
  • ServletContext – The ServletContext instance
  • HttpServletRequest – The HttpServletRequest instance for the current request
  • HttpServletResponse – The HttpServletResponse instance for the current request
  • HttpHeaders – Maintains the HTTP header keys and values
  • UriInfo – Query parameters and path variables from the URI called

It is a little confusing to have both an @Inject and @Context when both do the same job of injecting objects, but it is envisioned that future version of Java EE will bring more alignment of annotation use.

Where Is @Context Used?

It can be used to inject any of the above-mentioned instances into an instance field or directly into the resource method as a parameter.

Below is an example of the injecting into a method’s resource method parameter list:

public class EndpointResource {

public Response getHeaders(final @Context HttpHeaders httpHeaders){
    // Code here that uses httpHeaders

And here’s an example of injection into an instances field:

public class EndpointResource {

    private final @Context HttpHeaders httpHeaders;

    public Response getHeaders(){
        // Code here that uses httpHeaders

If you want to know more, take a look at this series of articles answering the question What is @Conext in JAX-RS used for?

Code Repository

The source code for this article is in my GitHub repository. Code for all my articles is in the ReadLearnCode Articles repository.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

java ee ,java ,jax-rs ,annotation ,context ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}