问题描述
根据HK2
我不知道如何使 ServiceLocator
找到带注释的类自动。
I don't know how to make ServiceLocator
find annotated classes automatically.
TestService
@Contract
public interface TestService {
}
TestServiceImpl
@Service
public class TestServiceImpl implements TestService {
}
Main
public static void main(String[] args) {
ServiceLocator locator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
TestService service = locator.getService(TestServiceImpl.class);
System.out.println(service); // null
}
结果总是 null
。我必须添加描述符
,以便 ServiceLocator
可以找到它。
The result is always null
. I have to add Descriptor
so the ServiceLocator
can find it.
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
自动查找带注释的类?我误解了什么吗?
How do I let ServiceLocator
find the annotated classes automatically ? Did I misunderstand something ?
推荐答案
你需要运行在您构建的类上,以便自动检测服务。 还有更多信息。
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.
该步骤在构建过程中的作用是创建一个名为META-INF / hk2-locator / default的文件,其中包含有关服务的信息。然后createAndPopulateServiceLocator调用读取这些文件并自动将这些服务描述符添加到返回的ServiceLocator中。
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.
这篇关于ServiceLocator如何在HK2中自动找到@Service和@Contact?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!