2
votes

I'm trying to use construction injection using both Jersey-injected @Context parameters and Guice-injected parameters.

This works (pure Jersey injection):

@Path("top")
public class TopLevel
{
  public TopLevel(@Context ResourceContext context)
  {
    ..
  }
}

This works (pure Guice injection):

@Path("top")
public class TopLevel
{
  @Inject
  public TopLevel(MyService service)
  {
    ..
  }
}

But this does not work:

@Path("top")
public class TopLevel
{
  @Inject
  public TopLevel(MyService service, @Context ResourceContext context)
  {
    ..
  }
}

because Guice does not know how to inject ResourceContext. If you look at JerseyServletModule you will notice it injects the following classes:

WebApplication, Providers, FeaturesAndProperties, MessageBodyWorkers, ExceptionMapperContext, HttpContext, UriInfo, ExtendedUriInfo, HttpRequestContext, HttpHeaders, Request, SecurityContext and HttpResponseContext

but not ResourceContext. Any ideas?

UPDATE: I don't think I can use field injection because I need the ResourceContext to instantiate another instance field. For example:

public class Foo
{
  public Foo(ResourceContext context) {}
}

public class Bar
{
  private final MyService service;
  private final ResourceContext context;
  private final Foo foo;

  @Inject
  public Bar(MyService service, @Context ResourceContext context)
  {
    this.foo = new Foo(context);
  }
}

If I were to instantiate ResourceContext after the constructor, I couldn't instantiate Foo.

1

1 Answers

0
votes

You should be able to inject it into an instance field using @Context. If that does not solve your problem (i.e. you really need to access it in the constructor), you can file an enhancement request at http://java.net/jira/browse/JERSEY and we will add it to the JerseyServletModule. The change is pretty minor.