gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:15:34 24 4
gpt4 key购买 nike

根据 HK2 @Service javadoc

Annotation placed on classes that are to be automatically added to an hk2 ServiceLocator.

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

测试服务

@Contract
public interface TestService {

}

测试服务实现

@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在您构建的类上,以便自动检测服务。还有更多信息here

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

关于java - ServiceLocator如何在HK2中自动找到@Service和@Contact?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23402814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com