Search code examples
javajerseyjersey-2.0hk2

HK2 annotations not being handled


I'm using HK2 through Jersey, and am looking to get @Immediate services working. In the process, I notice that (as it seems) none of the annotations for my services are getting registered. E.g., after spinning up my ServiceLocator and looking at my descriptor for a service annotated with @Singleton, it is still set as @PerLookup. My code for initiating my application handler is below:

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

My binder registers a service like so:

bindAsContract(ShouldHaveSingletonScope.class);

Looking at my ServiceLocator immediately after this, I see that the scope is not being pulled from the class (still @PerLookup). Is there something additional I need to specify to tell HK2 to parse class annotations? This seems like a pretty standard use case so I must be missing something.


Solution

  • There is a method on ServiceLocatorUtilities called addClasses

    So get access to the ServiceLocator and just do

    ServiceLocatorUtilities.addClasses(locator, ShouldHaveSingletonScope.class);
    

    The binders are very literal, and will only do what you tell it as opposed to looking at the classes directly.