users@jersey.java.net

Re: [Jersey] Using Guice with JAX-RS

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Thu, 02 Oct 2008 15:19:36 +0100

On Oct 2, 2008, at 2:23 PM, Gili wrote:

>
> Sorry, can you give an example code sniplet of the kind of code it
> picks up?
> Wouldn't Spring pick up fields annotated with Spring-annotations
> anyway?
>

Yes, but Jersey needs to perform injection as well and that depends on
the life-cycle. At the end of the email is code for the getInstance
method of the PerRequestProvider. Notice how it defers to the
ComponentProvider to get the instance that it can inject on.

The SpringResourceProvider is mapping @Scope annotations to the Jersey
ResourceProvider so the developer does not have to declare @Scope and
Jersey-based annotations.

Paul.

     public Object getInstance(ComponentProvider provider, HttpContext
context) {
         try {
             Object o = null;
             if (constructor == null) {
                 o = provider.getInstance(Scope.PerRequest, c);
             } else {
                 final Object[] params = new
Object[constructorInjectableParams.size()];
                 int index = 0;
                 for (Injectable i : constructorInjectableParams) {
                     params[index++] = (i != null) ?
i.getValue(context) : null;
                 }

                 o = provider.getInstance(Scope.PerRequest,
                     constructor, params);
             }
             rci.inject(context, provider.getInjectableInstance(o));
             return o;
         } catch (InstantiationException ex) {
             throw new ContainerException("Unable to create resource",
ex);
         } catch (IllegalAccessException ex) {
             throw new ContainerException("Unable to create resource",
ex);
         } catch (InvocationTargetException ex) {
             Throwable t = ex.getTargetException();
             if (t instanceof RuntimeException) {
                 // Rethrow the runtime exception
                 throw (RuntimeException)t;
             } else {
                 // TODO should a checked exception be wrapped in
                 // WebApplicationException ?
                 throw new ContainerException("Unable to create
resource", t);
             }
         }
     }