Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'am trying to Inject generic type with Guice. I have Repository< T > which is located in the Cursor class.

public class Cursor<T> {

    @Inject
    protected Repository<T> repository;

So when I create Cursor< User >, I also want the Guice to inject my repository to Repository< User >. Is there a way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
445 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have to use a TypeLiteral:

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

public class MyModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(new TypeLiteral<Repository<User>>() {}).to(UserRepository.class);
  }
}

To get an instance of Cursor<T>, an Injector is required:

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;

public class Main {

  public static void main(String[] args) {
    Injector injector = Guice.createInjector(new MyModule());
    Cursor<User> instance = 
        injector.getInstance(Key.get(new TypeLiteral<Cursor<User>>() {}));
    System.err.println(instance.repository);
  }
}

More details in the FAQ.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...