【问题标题】:How can I inject a generic parameter using Guice?如何使用 Guice 注入泛型参数?
【发布时间】:2012-01-22 05:54:05
【问题描述】:

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

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

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

【问题讨论】:

    标签: generics dependency-injection guice


    【解决方案1】:
    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);
        }
    }
    

    【讨论】:

    • @MairbekKhadikov,我打算这样做,谢谢,但是 SO 不允许您在 24 小时内接受自己的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2021-11-21
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    相关资源
    最近更新 更多