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

若如初见. 提交于 2019-11-28 13:37:26

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!