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

2022-01-21 00:00:00 java jersey hk2

根据 HK2 @Service javadoc

对要自动添加到hk2 服务定位器.

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

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

I don't know how to make ServiceLocator find annotated classes automatically.

测试服务

@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 可以找到它.

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 ?

推荐答案

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

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.

相关文章