Search code examples
javadependency-injectionjersey-2.0hk2

HK2 equivalent Assisted Injection with FactoryModuleBuilder


Thanks to migration to jersey 2 I need to migrate from guice to HK2. I have an Assisted injection approach for some of my dependencies which I couldn't get my head around to implement in HK2. It looks like it's supposed to be solved via Custom Injection Resolvers but I don't really see how. The examples are not clear enough for me..

Here is how it looks on Guice:

public interface MyFactory {
    public MyClass createMyClass(@Assisted String dynamicParameter);
    public HisClass createHisClass(@Assisted String dynamicParameter);
    ...
}

binder.install(new FactoryModuleBuilder().build(MyFactory.class));

public class MyClass {
   ...
   @Inject
   public MyClass(@Assisted String dynamicParameter, SomeService someOtherServiceInjectedAutomatically){
      ...
   }
}

How can I implement this on HK2?


Solution

  • After posting the question I thought of doing this:

    public class MyFactoryImpl implements MyFactory{
    
       private final SomeService someService;
    
       @Inject
       public MyFactoryImpl(SomeService someService){
          this.someService = someService;
       }
    
       public MyClass createMyClass(String dynamicParameter){
          return new MyClass(dynamicParameter, someService);
       }
    
       ...
    }