users@jersey.java.net

[Jersey] Re: Managed sub-resources

From: Marshall Pierce <marshall_at_mpierce.org>
Date: Sat, 07 Jan 2012 10:05:26 -0800

On 01/07/2012 09:31 AM, John Lister wrote:
> I may have missed the answer to this, but is it possible to have managed
> sub-resources such that I can inject beans, db resource, etc into them.
>
> For example if I have
> @Path("/child/")
> Child getChild(){
> return new Child();
> }
>
> then I have to either pass all the dependant resources as parameters or
> make them visible to the child class so that they can be accessed from
> it. The only way I can see is to make the child a bean and inject it
> into the parent and return the injected object, the downside is the
> extra object creation for every call.
>
> Is there an alternative, how does everyone else do it?
>
> Thanks
>
>
>
>
>
>

Looks like Jersey will not do this.
http://jersey.java.net/nonav/documentation/latest/user-guide.html
section 2.6 says:

----
Note that the runtime will not manage the life-cycle or perform any 
field injection onto instances returned from sub-resource locator 
methods. This is because the runtime does not know what the life-cycle 
of the instance is.
----
If you're using an IoC container that supports JSR-330, you can use a 
javax.inject.Provider (or a com.google.inject.Provider if you're using 
Guice anyway) to accomplish this tidily. Add the Provider<Child> as a 
constructor parameter, store it as a field, and call get() on it when 
you need a Child object.