Guice注入通用类型

时间:2014-07-09 15:00:01

标签: java generics guice

我正试图用Guice注入泛型类型。我有Repository< T>它位于Cursor类中。

public class Cursor<T> {

    @Inject
    protected Repository<T> repository;

所以当我创建Cursor&lt;用户&gt;,我也希望Guice将我的存储库注入Repository&lt;用户&gt;。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:20)

您必须使用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);
  }
}

要获取Cursor<T>的实例,需要Injector

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);
  }
}

更多详情in the FAQ