我(我想)理解依赖注入的目的,但我只是不明白为什么我需要Guice这样做(好吧,显然我不需要 Guice,但我的意思是为什么使用它会有好处).假设我有现有的(非Guice)代码,它是这样的:
public SomeBarFooerImplementation(Foo foo, Bar bar) {
this.foo = foo;
this.bar = bar;
}
public void fooThatBar() {
foo.fooify(bar);
}
Run Code Online (Sandbox Code Playgroud)
在某个更高级别,也许在我的main()中,我有:
public static void main(String[] args) {
Foo foo = new SomeFooImplementation();
Bar bar = new SomeBarImplementation();
BarFooer barFooer = new SomeBarFooerImplementation(foo, bar);
barFooer.fooThatBar();
}
Run Code Online (Sandbox Code Playgroud)
现在我基本上得到了依赖注入的好处,对吧?更容易测试等等?当然,如果你想要,你可以轻松地更改main()以从配置而不是硬编码中获取实现类名.
据我了解,在Guice做同样的事情,我会做类似的事情:
public SomeModule extends AbstractModule {
@Override
protected void configure() {
bind(Foo.class).to(SomeFooImplementation.class);
bind(Bar.class).to(SomeBarImplementation.class);
bind(BarFooer.class).to(SomeBarFooerImplementation.class);
}
}
@Inject
public SomeBarFooerImplementation(Foo foo, Bar, bar) {
this.foo = foo;
this.bar = bar;
}
public static …Run Code Online (Sandbox Code Playgroud)