ServiceLocator如何在HK2中自动找到@Service和@Contact?

根据HK2 @Service javadoc

放置在要自动添加到hk2 ServiceLocator的类上的注释。

我不知道如何使ServiceLocator自动查找带注释的类。

TestService的

 @Contract public interface TestService { } 

TestServiceImpl

 @Service public class TestServiceImpl implements TestService { } 

主要

 public static void main(String[] args) { ServiceLocator locator = ServiceLocatorUtilities.createAndPopulateServiceLocator(); TestService service = locator.getService(TestServiceImpl.class); System.out.println(service); // null } 

结果始终为null 。 我必须添加Descriptor以便ServiceLocator可以找到它。

 public static void main(String[] args) { ServiceLocator locator = ServiceLocatorUtilities.createAndPopulateServiceLocator(); DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class); DynamicConfiguration config = dcs.createDynamicConfiguration(); config.bind(BuilderHelper.link(TestServiceImpl.class).to(TestService.class).in(Singleton.class).build()); config.commit(); TestService service = locator.getService(TestServiceImpl.class); System.out.println(service); // TestServiceImpl instance } 

如何让ServiceLocator自动查找带注释的类? 我误解了什么吗?

您需要在构建的类上运行hk2-inhabitant-generator ,以便自动检测服务。 这里还有更多信息。

该步骤在构建过程中的作用是创建一个名为META-INF / hk2-locator / default的文件,其中包含有关服务的信息。 然后,createAndPopulateServiceLocator调用将读取这些文件,并自动将这些服务描述符添加到返回的ServiceLocator中。

仅供参考,我对依赖于居民文件感到非常沮丧,而不是具有运行扫描注释类的能力,我写了这个项目:

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

由于Eclipse / Maven /居民运行时生成器不能很好地运行,因此几乎不可能在没有运行时扫描的情况下调试在eclipse中使用HK2的代码。

HK2Utilities套餐位于中央:

  gov.va.oia HK2Utilities 1.4.1  

要使用它,您只需致电:

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

这将扫描运行时类路径中列出的包中的类,并自动使用它们填充服务定位器。

你不必使用这个模型生成居民文件 – 实际上,我发现它比居民处理代码更快(不是性能对这个一次性操作很重要)