users@jersey.java.net

[Jersey] Re: jersey-guice inject subresources

From: Christopher Piggott <cpiggott_at_gmail.com>
Date: Thu, 9 Dec 2010 18:14:22 -0500

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