How does ServiceLocator find @Service and @Contact automatically in HK2?

According to HK2 @Service javadoc

Annotations placed in classes that should be automatically added to hk2 ServiceLocator.

I do not know how to make ServiceLocator automatically search for annotated classes.

TestService

 @Contract public interface TestService { } 

TestServiceImpl

 @Service public class TestServiceImpl implements TestService { } 

home

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

The result is always null . I have to add a Descriptor so that 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 } 

How can I ServiceLocator find annotated classes automatically? I didn’t understand something?

+5
source share
2 answers

You need to run hk2-habitant-generator on your built-in classes in order to automatically detect services. There is also additional information.

What this step does during the build process is to create a META-INF / hk2-locator / default file with service information. Then the createAndPopulateServiceLocator call reads these files and automatically adds these service descriptors to the returned ServiceLocator.

+5
source

FYI, I was so upset because of the dependency on the occupant files, and did not have the ability to check the runtime of annotated classes, I wrote this project:

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

Since the Eclipse / Maven / habitant runtime generators did not play well, it was almost impossible to debug the code that used HK2 in eclipse without scanning at run time.

HK2Utilities package is available in the center:

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

To use it, you simply call:

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

This scans the execution class path for the classes in the listed packages and automatically populates them with a service locator.

You do not need to create files with this model, and in practice, I found that it works faster than the resident processing code (not that performance matters a lot for this one-time operation)

+5
source

Source: https://habr.com/ru/post/976337/


All Articles