users@hk2.java.net

Re: ServiceLocator.getService() failing for _at_Service-annotated classes

From: John Wells <john.wells_at_oracle.com>
Date: Wed, 04 Dec 2013 17:58:55 -0500

To use @Service you must

a) run the hk2-inhabitant-generator as part of your build in order to
produce the META-INF/hk2-locator/default file. You can look at this
file to see if it looks reasonable (it should have your services in there)

b) Ensure that when you boot hk2 you tell it to read those files in (it
does not do this automatically). The easiest way to do this is with this:

https://hk2.java.net/2.2.0-b25/apidocs/org/glassfish/hk2/utilities/ServiceLocatorUtilities.html#createAndPopulateServiceLocator%28%29

I do not currently monitor stackOverflow for hk2, but I will now!

On 12/4/2013 5:37 PM, cowwoc wrote:
> Hi,
>
> I've got something along the lines of:
>
> @Service
> public class TestClass
> {
> @Inject
> public TestClass()
> {
> }
> }
>
> public class MyApplication extends ResourceConfig
> {
> @Inject
> public MyApplication(ServiceLocator serviceLocator)
> {
> TestClass test = serviceLocator.getService(TestClass.class);
> }
> }
>
> but serviceLocator.getService(TestClass.class) returns null. What am I
> missing? Isn't HK2 supposed to auto-bind @Service-annotated classes
> somehow?
>
> PS: Do you monitor the "hk2" tag on Stackoverflow? I think it's a more
> efficient way of handling recurring questions.
>
> Thanks,
> Gili