如何使用Guice注入通用参数?

时间:2012-01-21 21:49:03

标签: generics dependency-injection guice

我发现了其他相关问题,但没有一个如此简单:

如何使用Guice绑定以下通用参数?

class A<T> {
   T a;
   @Inject A(T a) {
      this.a=a;
   }
}

1 个答案:

答案 0 :(得分:3)

public class TestGenericBinding {
   static class A<T> {
      T a;
      @Inject A(T a) {
         this.a=a;
      }
   }

    @Test public void bindingWorked() {
       Injector injector = Guice.createInjector(new AbstractModule() {

         @Override
         protected void configure() {
            bind(Integer.class).toInstance(123);
            bind(new TypeLiteral<A<Integer>>() {});
         }
      });
       A<Integer> a = injector.getInstance(
          Key.get(new TypeLiteral<A<Integer>>(){}));
       assertEquals(new Integer(123),a.a);
    }
}