users@hk2.java.net

Re: ServiceLocator.getService(Class<?>) vs createAndInitialize(Class<?>)

From: John Wells <john.wells_at_oracle.com>
Date: Fri, 18 Apr 2014 07:55:42 -0400

There are several difference. The biggest one is that the object
returned from createAndInitialize is NOT managed at all by HK2, and
hence cannot be used for injection in any other object. There are other
differences as well, here are a few I've thought of:

* createAndInitialize cannot take an interface or an abstract class, but
only a concrete class
* createAndInitialize ignores any scope on the object (i.e., even if the
class is in Singleton scope every call to createAndInitialize will
create a new instance)
* createAndInitialize will never proxy the class
* objects returned from createAndInitialize will never be injected into
other hk2 services

Hope that helps!

On 4/17/2014 11:19 PM, cowwoc wrote:
> Hi,
>
> What's the difference between ServiceLocator.getService(Class<?>) and
> createAndInitialize(Class<?>) methods? I read the Javadoc over and
> over but I don't see the difference. Doesn't getService() also inject
> and post-construct the returned instance?
>
> I notice one of Jersey's methods does this:
>
> T component = serviceLocator.getService(clazz);
> return component == null ?
> serviceLocator.createAndInitialize(clazz) : component;
>
> Why would getService() return null but createAndInitialize() work?
>
> Thanks,
> Gili