News Ticker

JAX-RS: What is @Context?

What is @Context Used For in JAX-RS?

Inject Twelve Context Object

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 the HTTP request. It behaves just like to @Inject and the @Autowired annotations in Java EE and Spring respectively.

The object instances that it can inject are the following:

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 about 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:

@Path("/")
public class EndpointResource {

@GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getHeaders(final @Context HttpHeaders httpHeaders){
 // Code here that uses httpHeaders
 }
}

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

@Path("/")
public class EndpointResource {

private final @Context HttpHeaders httpHeaders;

@GET
 @Produces(MediaType.APPLICATION_JSON)
 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.

Further Reading

I often publish articles about Java EE on readlearncode.com and have posted an interesting series of blog articles looking at the JAX-RS API in more detail. These articles discuss handling bean validation failure, working with @Consumes and @Produces annotations, and JAX-RS Resource Entities, and take you deeper into this core Java API.

Learn More

Have you considered online video training from Lynda.com? The site offers an extensive range of Java EE technologies course for beginners to experts. So, if you are just taking your first steps into the exciting world of enterprise Java then you will love my course Learning Java Enterprise Edition. It is a packed full two-hour course spanning the essential APIs in the Java EE platform.

Your learning does not end with this course. Once completed, you can expand your knowledge by learning how to build an online bookshop using RESTful APIs, build your own chat application with the WebSocket API and become a JSON master with the JSON-Processing course. There are many more courses on the roadmap, so pop over to Lynda.com and get ready to give your Java EE career a boost.

Leave a Reply

%d bloggers like this: