How to inject an unbound generic type in HK2?

2019-08-13 06:24发布

问题:

I'm writing a webservice using Jersey 2.9 and I'm also using HK2 for DI. I have a class which handles a connection to a database which can be instantiated like that:

public class DBHandler {
  private DBConnection<?> dbConnection;

  @Inject
  public DBHandler(DBConnection<?> dbConnection) {
    this.dbConnection = dbConnection;
  }
}

As you can see, field dbConnection has an unbounded generic type. By binding implementation currently looks like follows:

public class MyProductionBinder extends AbstractBinder {

   @Override
   protected void configure() {
     bind(ClientServerDBConnection.class).to(new TypeLiteral<DBConnection<?>>() {});
   }
}

Howevery, during runtime the following exception is thrown;

Caused by: org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=DBConnection<?>,parent=DBHandler,qualifiers={}),position=0,optional=false,self=false,unqualified=null,731556610)

If I turn the variable declaration in DBHandler into a raw type like this:

public class DBHandler {
  private DBConnection dbConnection;

  @Inject
  public DBHandler(DBConnection dbConnection) {
    this.dbConnection = dbConnection;
  }
}

it works like expected.

Do I miss something or is it not possible in HK2 to specify such a binding?

Best regards,
Andreas

回答1:

HK2 uses the same rules for type matching that CDI does, which does mean that your use case of injecting DBConnection will NOT work while just using DBConnection will work. If this is an important enough use case for you enter a Jira and we can think about having HK2 deviate from the CDI rules for this case. I also think that DBConnection would also work.