2

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.

Zack
  • 1,181
  • 2
  • 11
  • 26

2 Answers2

3

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.

jwells131313
  • 2,364
  • 1
  • 16
  • 26
  • Looks like this method does indeed honor the class annotations through DynamicConfiguration, where registering a class in a Binder does not. This seems very counterintuitive and frustratingly limiting. Especially, given the fact that ApplicationHandler accepts a custom Binder as a parameter. Thanks for the answer though! – Zack Feb 13 '14 at 21:57
  • 1
    It would be a good idea to enter a Jira asking for a bind method, perhaps, like "analyze(Class> clazz...)" on the binder for cases such as yours – jwells131313 Feb 14 '14 at 00:59
  • 1
    What is locator variable? where do I init it from? – Dejell Feb 27 '14 at 17:12
1

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.

kppk
  • 52
  • 6
  • 9
    So, this means that HK2 can't pull annotations directly off the class? Whats the point of annotating the class then? – Zack Feb 13 '14 at 06:25
  • That has been my frustration as well. See: http://stackoverflow.com/a/35191749/2163960 – user2163960 Feb 04 '16 at 03:12