I'm trying to inject a custom variable into a method. Very simply, I'd like
to have a method like:
@GET
@Produces(MediaType.TEXT_HTML)
public Response doGet(RemoteUser remoteUser) throws ServiceException;
Where RemoteUser is a custom type that wraps the HttpSession and some other
stuff. We do this *a lot* in a Jersey1 application and I thought it'd be
easier to do in Jersey2 with all the new injection stuff. Been at this for
a few *days* now and finally have something that seems to work. Namely:
(1) Application extends ResourceConfig and registerInstance's a custom
Binder. (why??)
(2) custom Binder extends AbstractBinder and must be annotated with
@Provider (why??).
(3) Create a provider. This provider must implement ContextResolver
and org.glassfish.hk2.api.Factory. (why???). The factory must be
request-scoped so it can get the HttpServletRequest @Inject'd but you can't
actually put @RequestScoped on the factory. Instead you've got to
bindFactory(RemoteUserProvider.class).to(RemoteUser.class).in(RequestScoped.class);
in your Binder.
(4) Annotate the above the method with @Context
So this seems to work. RemoteUser is getting injected with a non-null
session. But I have to ask: (1) is there an easier way to do this? (2) is
there a more portable way to accomplish this without implementing strange
hk2 apis? and (3) Is there a way to do this with less code (creating a
*Provider that implements ContextResolver and Factory for every Form seems
fantastically tedious!).
(Got to say, I'm having very mixed feelings about Jersey2. It really seems
like things that were trivial to do in Jersey1 require some real *strange*,
black magic in Jersey2. If there was some documentation about this it might
be tolerable but we're flying completely blind. This experience makes me
very, very wary of continuing with this upgrade!)