当创建一个注入器来创建一个对象时,我们是否需要为它的间接依赖包含模块?
例如,在下面的代码中,我们应该如何在 main() 中创建注入器?
public class Foo {
private Bar bar;
@Inject
public Foo(Bar bar) {
this.bar = bar;
}
public static void main(String[] argv) {
Injector injector = Guice.getInjector(new BarModule());
// or Injector injector = Guice.getInjector(new BarModule(), new BarDepModule());
Foo foo = injector.getInstance(Foo.class);
}
}
//=====================
public interface Bar {}
public class BarImp {
private BarDep barDep; // Dependency of Bar
@Inject
public Bar(BarDep barDep) {
this.barDep = barDep;
}
}
//=====================
当然,BarDep 应该有一个绑定。问题是我们应该明确加载 BarDepModule 还是应该由 BarModule 负责?