HK2 annotations are not processed

I am using HK2 through Jersey and I want to get @Immediate to work. In the process, I notice that (as it seems) none of the annotations of my services are registered. For example, after expanding my ServiceLocator and looking at my service descriptor annotated with @Singleton, it is still set as @PerLookup. My code to run my application handler is below:

ApplicationHandler handler = new ApplicationHandler(resourceConfig, new AbstractBinder() { ... }); 

My binder registers the following service:

 bindAsContract(ShouldHaveSingletonScope.class); 

Looking at my ServiceLocator right after that, I see that the area is not retrieved from the class (still @PerLookup). Is there anything extra I need to specify in order to tell HK2 to parse class annotations? This seems like a pretty standard use case, so I'm missing something.

+2
source share
2 answers

There is one method in ServiceLocatorUtilities called addClasses

So get access to ServiceLocator and just do

 ServiceLocatorUtilities.addClasses(locator, ShouldHaveSingletonScope.class); 

The attachments are very literal and will do what you say, and not look at the classes directly.

+3
source

This should work:

 bindAsContract(ShouldHaveSingletonScope.class).in(Singleton.class); 

You can configure the locator manually using Binder

-or -

use hk2 annotations, run hk2-inhabitants-generator (see hk2 doc ) which will generate the META-INF/hk2-locator/default file, then you will need to create your own ComponentProvider (see jersey doc ) to populate the services locator from of this.

+1
source

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


All Articles