如何在Google Guice中创建实现的实例

ste*_*beg 2 java dependency-injection inject guice

我是Google Guice的新手,需要一点帮助。我创建了一个像这样的模块:

public interface Foo {
  Bar doSomething();
}

public class MyFoo implements Foo {
  Bar doSomething() {
    // create an instance of MyBar
  }
}

public interface Bar {
  void run();
}

public interface MyBar implements Bar {
  void run();
}

public class MyModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(Foo.class).to(MyFoo.class);
  }      
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:在类“ MyFoo”中创建MyBar实例的正确方法是什么?只是这样做是错误的:

public class MyFoo implements Foo {
  Bar doSomething() {
    MyBar mybar = new MyBar();
    return mybar;
  }
}
Run Code Online (Sandbox Code Playgroud)

是否可以在需要时通过MyModule注入MyBar的新实例,还是必须在MyBar的构造函数中注入工厂才能创建MyBar实例?如果必须使用工厂,是否可以控制通过模块生成的实现?

Ste*_*ler 5

也许您在寻找供应商?提供者或多或少是Guice API的一部分的工厂,因此您不必实现它们。

public class MyFoo implements Foo {
  @Inject Provider<MyBar> myBarProvider;

  Bar doSomething() {
    return myBarProvider.get(); // returns a new instance of MyBar
  }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参见https://github.com/google/guice/wiki/InjectingProviders