wg26nq
Last Updated: February 25, 2016
·
6.405K
· mdonkers

Jersey 2 Custom Injection of Method Parameters

Problem Description

In our custom framework built upon Jersey 2.x, we rely on the injection of certain method parameter inside Jersey Resources. For example in a Servlet Filter we do some parsing of cookies and HTTP headers to create a user identity object. We want to inject this object as method parameter.
For Spring MVC and Jersey 1.x, this was no problem. However Jersey 2.x seems to have some constraints. For example the "@Context" annotation is not allowed for HTTP GET methods (because the GET does not support an entity body).

Implementation Explained

By creating a custom annotation and a ValueFactoryProvider I managed to overcome the problems. The full solution can be found below, but let me explain the most important parts.

First of all you need to create a custom annotation. Don't forget the RetentionPolicy set to Runtime. This annotation can later be used in the Jersey Resource to annotate the method parameter.

Next create a ValueFactoryProvider (by extending Jersey's AbstractValueFactoryProvider). Make sure it will fetch / inject the correct object instances. The 'provide()' method for the implemented AbstractContainerRequestValueFactory needs to return the object to be injected. In this class you may use the @Context annotation to inject e.g. the Request object and pull stuff stored on the session.

Finally the ValueFactoryProvider needs to be registered as a HK2 binder, so that when the DI framework (HK2) sees your annotation, it will know where to resolve the objects.

Full Solution Link

Full solution GIST: "Jersey 2 custom injection" GIST

3 Responses
Add your response

10811

You should be able to inject the HttpServletRequest using @Context even on GET. Is that not the case?

over 1 year ago ·
10817

Nope. Indeed this worked for Jersey 1, but is broken in Jersey 2.x.
It's a known bug however and will be fixed in a future version.
This is the bug-report: https://java.net/jira/browse/JERSEY-1960

over 1 year ago ·
10860

Jersey 2.4.1 is released where the @Context annotation to inject HttpServletRequest is fixed...

over 1 year ago ·