users@jersey.java.net

[Jersey] Re: jersey-guice inject subresources

From: Paul Sandoz <Paul.Sandoz_at_oracle.com>
Date: Mon, 13 Dec 2010 10:54:18 +0100

Hi Christopher,

Touche, assisted injected is a nice way. I tend to prefer if the
factory interface is nested with the bound class if that interface is
not reused in other places.

There is a simpler way, but i prefer the assisted inject approach
because it means different classes do not need to know parameter names.

@RequestScoped
public class SubResource {
  private int itemId;

  // The sub-resource needs to know the parameter name of the super
resource
  @PathParam("itemId") String itemId;

  // Note that constructor injection of JAX-RS @*Param is not
currently supported with Guice

  @GET public String getItemDetails()
  {
    return "Details for item " + itemId + "\r\n";
  }
}

Paul.

On Dec 10, 2010, at 12:14 AM, Christopher Piggott wrote:

> Paul (and anybody else who's interested)
>
> I asked this question:
>
>
> On Thu, Dec 9, 2010 at 9:44 AM, Christopher Piggott > This still
> doesn't work as I wanted, because the path to the sub
>> resource is /item/123/123 not just /item/123 ... what's the "right"
>> way to fix this, without forcing the sub-resource to have to parse
>> out
>> the URL again?
>
>
>
> I found a solution to my problem, using guice 2 assisted injection.
> It's a little crazy looking but it works.
>
> I created a SubResourceFactory interface:
>
>
> public interface SubResourceFactory {
> public SubResource create(int itemId);
> }
>
> Then I used assisted injection. First, the sub-resource locator
> method:
>
> @Path("{itemId}")
> public PlatformHosSubResource getItem(
> @PathParam("itemId") int itemId,
> @InjectParam SubResourceFactory provider)
> {
> return provider.create(itemId);
> }
>
>
> That then creates a SubResource, which is a little different than
> before in that it has a constructor now:
>
> @RequestScoped
> public class SubResource {
> private int itemId;
>
> @Inject SubResource(@Assisted int injectedItemId)
> {
> this.itemId = injectedItemId;
> }
>
> @GET public String getItemDetails()
> {
> return "Details for item " + itemId + "\r\n";
> }
> }
>
> Then, the magic in the module to make this all happen:
>
> Provider<SubResourceFactory> subResourceProvider =
> FactoryProvider.newFactory(SubResourceFactory.class,
> SubResource.class);
> bind(SubResourceFactory.class).toProvider(subResourceProvider);
>
>
> This is the first time I have ever used guice assisted injection.
> It's crazy stuff, and I'm so happy it works I'm bouncing off the
> walls. Even if it isn't an optimal solution (I'm open to better
> ones!) I still think it's very cool.
>
> :)
>
> --Chris