users@jersey.java.net

Re: [Jersey] Using Guice with JAX-RS

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 07 Oct 2008 17:46:23 +0200

On Oct 7, 2008, at 5:35 PM, Gili wrote:

>
>
> Paul Sandoz wrote:
>>
>>> This means that a default scope (which just happens to be
>>> PerRequest)
>>> with a Guice scope is okay, but @PerRequest with a Guice scope is
>>> not.
>>>
>>
>> What if there is a class is annotated with
>> @com.google.inject.Singleton and not annotated with @PerRequest? then
>> there will be a conflict with what Guice provides and what Jersey
>> expects. For example, given the following:
>>
>> @Path("xyz")
>> @com.google.inject.Singleton
>> public class XYZ {
>> @Context UriInfo ui;
>> }
>>
>> Jersey will think an instance returned by the component provider is a
>> new instance and thus inject a direct instance of UriInfo that is
>> associated with the current request onto XYZ. Any concurrent or
>> subsequent requests to XYZ will result in odd behavour when accessing
>> state of "ui" because they will be accessing URI information of the
>> firs request that resulting in instantiation of XYZ.
>>
>
> It sounds to me like there is a fundamental difference in how Jersey
> and
> Guice injection works and as a result any Guice user will find this
> behavior
> very confusing.

Note that @Context is a JAX-RS annotations. The injection rules are
specified by JAX-RS and is independent of Guice and it's injection
rules.


> If the above code was a normal Guice application then
> UriInfo would have a different scope than its surrounding XYZ class.
> For
> example, this is typical usage under Guice:
>
> @Path("xyz")
> @com.google.inject.Singleton
> public class XYZ {
> @RequestScoped
> @Context
> Provider<UriInfo> ui;
> }
>
> This means that XYZ would get constructed once and ui.get() would
> return a
> new instance every HTTP request (but return the same value within
> the same
> HTTP request).
>
> We need to resolve the Jersey-Guice paradigms first before
> implementing
> anything. If I understand you correctly, fields have no concept of a
> scope
> under Jersey.
> Fields share the scope of their containing class. Is this
> correct?
>

No. They are defined by the InjectableProvider instances that support
them. We are trying to complicate things too much!

I would not expect a developer to have to additionally annotate JAX-RS
specific annotations with additional Guice ones or utilize them
differently from what JAX-RS specifies. The behavior i described is an
*optimization* that the developer does not have to be aware of. They
do not care as long as an instance of UriInfo gets injected by Jersey
that provides URI information of the current request.

Lets differentiate between the resposibilities such that Guice injects
what Guice understands and Jersey injects what Jersey understands
according to what is specified by JAX-RS.

Paul.