users@jersey.java.net

Re: [Jersey] Dependency resolution for container request and response filters

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Mon, 18 Jan 2010 11:04:20 +0000

On Jan 14, 2010, at 2:56 PM, Brian Gilstrap wrote:

>
> On Jan 14, 2010, at 6:27 AM, Paul Sandoz wrote:
>
>> Hi Brian,
>>
>> Since you are using Spring you could register those filter classes
>> as singleton spring beans and Jersey will defer to Spring to obtain
>> references to those classes. Then you can use Spring-based
>> injection, including constructor or field-based injection as
>> supported by Spring. Will that work for you?
>>
>> Otherwise there is a Jersey specific way i can send more details on
>> if the Spring approach is not suitable.
>
> You have hit upon a related issue. I would like to understand how to
> use Jersey with Spring and with other IOC approaches. I need to go
> back and make a copy of my code which does not use Spring and figure
> out how to make everything work. In particular, I want to know what
> other IOC approaches work with Jersey, both in terms of things like
> my filters and in terms of resource objects that are instantiated by
> Jersey but which need to have additional objects injected for use.
>
> So, that leads me to two things:
>
> 1) Is there an example of a singleton spring bean in the sample code
> I can learn from? (I tried doing this once in the past and had some
> trouble, so I punted and took a different route at the time)
>

Perhaps the Spring annotations sample is sufficient?

http://download.java.net/maven/2/com/sun/jersey/samples/spring-annotations/1.1.4.1/spring-annotations-1.1.4.1-project.zip


> 2) Can you please tell me the Jersey-specific way to do the
> dependency injection?
>

You can register your own InjectableProvider implementations, either
by scanning or explicitly via the Application/ResourceConfig.

There are two helper classes you can use:

https://jersey.dev.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/inject/SingletonTypeInjectableProvider.html
https://jersey.dev.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/inject/PerRequestTypeInjectableProvider.html

that provide partial implementations of InjectableProvider.

One technique is to register you own Application/ResourceConfig and
inject the ServletContext or ServletConfig on the Application/
ResourceConfig to get access to some config information then register
singleton instances of InjectableProvider.

Note that i try to recommend that developers use Guice (my preference)
or Spring to do IoC if they do not mind such dependencies. Otherwise,
Jersey can sort of do it but it is not as fully functionality nor is
the design where i would like it to be (if i could do it again it
would just like Guice e.g. any Jersey 2.0 effort :-) ).

Paul.