问题
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.
回答1:
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.
回答2:
This should work:
bindAsContract(ShouldHaveSingletonScope.class).in(Singleton.class);
You can either configure the locator manually using Binder
-or-
use hk2 annotations, run hk2-inhabitants-generator
(see hk2 doc) which will generate META-INF/hk2-locator/default
file, then you will need to create your own ComponentProvider
(see jersey doc) to populate service locator from that.
来源:https://stackoverflow.com/questions/21744297/hk2-annotations-not-being-handled