Inject Generic Implementation using Guice

In order to use generics with Guice you need to use the TypeLiteral class to bind the generic variants. This is an example of how you’re Guice injector configuration could look like:

package your-application.com;

import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;

public class MyModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(new TypeLiteral<Repository<Class1>>(){})
      .to(new TypeLiteral<MyRepository<Class1>>(){});
  }
}

(Repository is the generic interface, MyRepository is the generic implementation, Class1 is the specific class used in the generics).

Leave a Comment