在Guice注入一家通用工厂

Chr*_*way 12 java generics dependency-injection guice

以下代码是生成Bar<T>给定a 的工厂示例Foo<T>.工厂并不关心什么T是:对于任何类型T,它都可以制造Bar<T>一个Foo<T>.

import com.google.inject.*;
import com.google.inject.assistedinject.*;

class Foo<T> {
  public void flip(T x) { System.out.println("flip: " + x); }
}

interface Bar<T> {
  void flipflop(T x);
}

class BarImpl<T> implements Bar<T> {
  Foo<T> foo;

  @Inject
  BarImpl(Foo<T> foo) { this.foo = foo; }

  public void flipflop(T x) { foo.flip(x); System.out.println("flop: " + x); }
}

interface BarFactory {
  <T> Bar<T> create(Foo<T> f);
}

class Module extends AbstractModule {
  public void configure() {
    bind(BarFactory.class)
      .toProvider( 
          FactoryProvider.newFactory( BarFactory.class, BarImpl.class ) 
                   );
  }
}

public class GenericInject {
  public static void main(String[] args) {
    Injector injector = Guice.createInjector(new Module());

    Foo<Integer> foo = new Foo<Integer>();
    Bar<Integer> bar = injector.getInstance(BarFactory.class).create(foo);
    bar.flipflop(0);
  }
}
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,我从Guice得到以下错误:

1) No implementation for BarFactory was bound.
  at Module.configure(GenericInject.java:38)

2) Bar<T> cannot be used as a key; It is not fully specified.
Run Code Online (Sandbox Code Playgroud)

我可以在Guice文档中找到泛型的唯一参考说明使用a TypeLiteral.但是我没有文字类型,我有一个与工厂无关的通用占位符.有小费吗?

Ste*_* B. -1

如果您将 guice 视为类似于 spring 的连接系统,那么连接通用实例就没有意义。您将特定实例连接到键,以便当另一个实例化类使用 @Inject BarFactory 标记某些内容时,您可以获得特定的创建实例。

由于您的实现是通用的,因此您没有提供足够的信息来注入特定实例。虽然我没有使用过factoryprovider,但我的假设是您需要将 Barfactory 绑定到完全参数化的实例,例如BarImpl<Concrete>而不是 BarImpl )

顺便说一句,由于您要绑定 BarFactory.class 如果您想绑定多个实例,您将不得不以某种方式改变它们,无论是通过名称,还是类似(尚未检查语法,但是)

bind(BarFactory.class).annotatedWith(Names.named("name1"))
      .toProvider( 

or by generics, bind(BarFactory<Concrete>).toProvider...
Run Code Online (Sandbox Code Playgroud)