Search code examples
javajerseyhk2

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


According to HK2 @Service javadoc

Annotation placed on classes that are to be automatically added to an 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
}

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
}

How do I let ServiceLocator find the annotated classes automatically ? Did I misunderstand something ?


Solution

  • 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.

    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.