users@jersey.java.net

Re: [Jersey] Using Guice with JAX-RS

From: Gili <cowwoc_at_bbs.darktech.org>
Date: Thu, 2 Oct 2008 09:52:07 -0700 (PDT)

Hi Paul,

I don't think a SpringResourceProvider-style implementation is going to work
for guice, because there are 3rd-party scopes floating around.

Instead of mapping Spring/Guice scopes to Jersey's built-in resource
providers, why don't they simply implement their own resource provider which
works regardless of the scope? What's wrong with the following
ResourceProvider implementation?


import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.api.model.AbstractResource;
import com.sun.jersey.spi.resource.ResourceProvider;
import com.sun.jersey.spi.service.ComponentProvider;
import com.sun.jersey.spi.service.ComponentProvider.Scope;

/**
 * Uses Guice to inject resources.
 *
 * @author Gili Tzabari
 */
public class GuiceResourceProvider implements ResourceProvider
{
        private Class<?> resourceClass;

        @Override
        public void init(ComponentProvider componentProvider, ComponentProvider
resourceProvider,
                AbstractResource resource)
        {
                this.resourceClass = resource.getResourceClass();
        }

        @Override
        public Object getInstance(ComponentProvider provider, HttpContext context)
        {
                try
                {
                        return provider.getInstance(Scope.Undefined, resourceClass);
                }
                catch (InstantiationException e)
                {
                        throw new RuntimeException(e);
                }
                catch (IllegalAccessException e)
                {
                        throw new RuntimeException(e);
                }
        }
}


I see PerRequestProvider is going through a lot of trouble to handle
constructors, but I don't believe this is an issue for Guice because it
limits you to at most one injectable constructor.

Can you please explain how this differs in Spring or Jersey? I'm not
familiar with the concept of having multiple injectable constructors. How
does Spring know which one you want to inject with? How does Jersey decide
which one *it* wants to use?

Thanks,
Gili


Paul Sandoz wrote:
>
> On Oct 2, 2008, at 3:31 PM, Gili wrote:
>
>>
>> In other words, Spring can inject the fields just fine but later on
>> when
>> Jersey needs an instance some time later on it wouldn't know how to
>> get it?
>
>>
>> This mechanism ensures that the instances are registered both with
>> Jersey
>> and with Spring?
>>
>
> Yes. Since Jersey is responsible for deploying those classes as
> resource classes and invoking methods on them.
>

-- 
View this message in context: http://n2.nabble.com/Using-Guice-with-JAX-RS-tp1127230p1134358.html
Sent from the Jersey mailing list archive at Nabble.com.