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

问题描述 投票:6回答:2

根据HK2 @Service javadoc

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

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

测试服务

@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自动找到带注释的类?我误解了什么吗?

java jersey hk2
2个回答
5
投票

您需要在构建的类上运行hk2-inhabitant-generator才能自动检测服务。还有更多信息here

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


5
投票

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

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

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

HK2Utilities套餐位于中央:

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

要使用它,您只需致电:

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

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

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

- -编辑 - -

我仍然维护这段代码 - 目前的版本是:

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

项目位置现在是:https://github.com/darmbrust/HK2Utilities

© www.soinside.com 2019 - 2024. All rights reserved.