How does ServiceLocator find @Service and @Contact automatically in HK2?

You need to run the hk2-inhabitant-generator over your built classes in order to get automatic detection of services. There is more information here as well.

What that step does in the build process is to create a file named META-INF/hk2-locator/default with information about services. The createAndPopulateServiceLocator call then reads those files and automatically adds those service descriptors into the returned ServiceLocator.


FYI, I was so frustrated with the reliance on the inhabitant files rather than having the capability for runtime scanning of annotated classes, I wrote this project:

https://github.com/VA-CTT/HK2Utilities

Since Eclipse / Maven / inhabitant runtime generators wouldn't play nice, it was nearly impossible to debug code that made use of HK2 in eclipse without runtime scanning.

The HK2Utilities package is available in central:

<dependency>
    <groupId>gov.va.oia</groupId>
    <artifactId>HK2Utilities</artifactId>
    <version>1.4.1</version>
</dependency>

To use it, you just call:

ServiceLocator locator = HK2RuntimeInitializer.init("myName", false, new String[]{"my.package.one", "my.package.two"});

This will scan the runtime classpath for classes in the packages listed, and automatically populate the service locator with them.

You don't ever have to generate inhabitant files with this model - and in practice, I found it to be faster performing than the inhabitant processing code as well (not that the performance matters much for this one-time operation)

---edit---

I still maintain this code - the current release is:

<dependency>
    <groupId>net.sagebits</groupId>
    <artifactId>HK2Utilities</artifactId>
    <version>1.5.2</version>
</dependency>

And the project location is now: https://github.com/darmbrust/HK2Utilities

Tags:

Java

Jersey

Hk2