小编ste*_*beg的帖子

如何在Google 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实例?如果必须使用工厂,是否可以控制通过模块生成的实现?

java dependency-injection inject guice

2
推荐指数
1
解决办法
1913
查看次数

标签 统计

dependency-injection ×1

guice ×1

inject ×1

java ×1