users@jersey.java.net

Pattern for sub-resources with injection and arguments

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 22 Jun 2009 14:18:05 +0200

Hi,

Guice 2.0 has a nice pattern for the case when obtain an instance from
a DI framework where additional non-injected parameters need to be
passed:

   http://code.google.com/docreader/#p=google-guice&s=google-
guice&t=AssistedInject

I know a number of developers have been scratching their heads other
this one (including me).

If you use Guice to manage your resources then you can use
AssistedInject, which i presume should work with Jersey as i have not
tested it.

Otherwise you can follow a factory pattern:

  public class MyResourceFactory {

     private final UriInfo ui;

     public class MyResourceFactory(@Context UriInfo ui) {
         this.ui = ui;
     }

     public MyResource create(String param) {
        return new MyResource(param);
     }

     public class MyResource {
         private final String param;

         public class MyResource(String param) {
             this.param = param;
         }
         ...
     }
  }


  @Path("{id}")
  public MyResource get(@Context ResourceContext rc, @PathParam("id")
String id) {
      return rc.get(MyResourceFactory.class).create(id);
  }

Paul.