Search code examples
javajerseyjersey-2.0hk2

Bind service class with generic


I have one interface with generic

@FunctionalInterface
public interface GenericInterface<T> {

    Optional<T> doSmth(long Id);
}

I have two implement classes, for instance GenericInterfaceImpl and GenericInterfaceImplImpl, they both are using own class as a generic in one method

public class GenericInterfaceImpl
    implements GenericInterface<OwnClass> {
}

public class GenericInterfaceImplImpl
    implements GenericInterface<OwnClass2> {
}

I have another two classes, that which should use dependencies of above services

public class Class1 {
private final GenericInterface<OwnClass> gen;
@Inject
public Class1(GenericInterface<OwnClass> gen) {
this.gen = gen;
}
}

public class Class2 {
private final GenericInterface<OwnClass2> gen2;
@Inject
public Class2(GenericInterface<OwnClass2> gen2) {
this.gen2 = gen2;
}
}

ServiceBinder class

bind(GenericInterfaceImpl.class).to(GenericInterface.class);
bind(GenericInterfaceImplImpl.class).to(GenericInterface.class);

After running application, assuming, that I have registered ServiceBinder, I've got this error

Caused by: org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=GenericInterface,parent=Class1 etc.)

How to bind it correctly?


Solution

  • After 8 hours of searching, I've found solution

       bind(GenericInterfaceImpl.class).to(new TypeLiteral<GenericInterface<OwnClass>>() {});
       bind(GenericInterfaceImplImpl.class).to(new TypeLiteral<GenericInterface<OwnClass2>>(){});