users@jersey.java.net

Re: [Jersey] injecting _at_Context fields on sub resources...

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Tue, 20 Apr 2010 17:39:56 +0200

Hi James,

>> Injecting after instantiation sort of breaks the life-cycle contract
>> (injection onto fields or setter methods should occur after
>> construction and
>> before any post construct method is invoked).
>
> Though if I'm creating the sub resource object by hand, there will be
> no post construction method invoked anyway - we're already outside of
> the IoC post construction rules, since the IoC container isn't
> creating the object - we're just invoking a constructor on the object.
>
> It would be nice to be able to enable JAXRS injection into sub
> resources - maybe as an optional extension?; it would leave the code
> more dry. I find when creating sub resources I tend to create a custom
> constructor for the root resource to invoke to keep code small & DRY.
> It does seem a bit odd that you can share a base class/trait between a
> root and sub resource and its not possible to have any of the
> injections fire in the sub resources.
>
> I wonder how hard it'd be to add as an option? I remember seeing in
> both Guice and Spring for example a one line method call to perform
> any remaining injections on an object if you create it outside of the
> IoC container?
>

One problem is for the code that processes the return instance from
the sub-resource locator to determine whether the returned instance is
managed or not (it could be managed by Jersey, Guice, Spring, CDI or
whatever is plugged in). As we do not want to perform re-injection.

Currently there is no way in Jersey to determine if an instance is
managed, or if the class of the instance is "in-scope". Is it possible
in Guice/Spring/CDI to determine that?


If we can assume the case of when the instance is not managed it is
reasonably easy to support injection. Perhaps we could support an
annotation on a sub-resource locator and leave it up to the developer
to do the right thing? We could also expose out the injection support
in ResourceContext.

   ResourceContext.inject(Object o);


I would really like a type safe way of doing constructor injection
with additional parameters but have not worked out a way that could be
like Guice's assisted inject and work across the DI containers.

Paul.