我们什么时候要注入 class 而不是实例?
When do we want to inject a class instead of instance?
由于通常 classes 是通过提供 0 个或多个初始参数构造的,因此使用实例注入听起来很自然。
我们什么时候要将 class 绑定到子 class 而不是子 class 的实例?
当您绑定 class 时,您将解决依赖关系的责任委托给了 Guice,而实例注入则将其交给了您;例如,如果您为需要 Bar
的 Foo
使用实例注入,您现在要负责手动注入 Bar
,这基本上破坏了使用 Guice 的大部分意义。
From the Guice docs on instance injection(强调)
You can bind a type to a specific instance of that type. This is
usually only useful only for objects that don't have dependencies of
their own, such as value objects:`
由于通常 classes 是通过提供 0 个或多个初始参数构造的,因此使用实例注入听起来很自然。
我们什么时候要将 class 绑定到子 class 而不是子 class 的实例?
当您绑定 class 时,您将解决依赖关系的责任委托给了 Guice,而实例注入则将其交给了您;例如,如果您为需要 Bar
的 Foo
使用实例注入,您现在要负责手动注入 Bar
,这基本上破坏了使用 Guice 的大部分意义。
From the Guice docs on instance injection(强调)
You can bind a type to a specific instance of that type. This is usually only useful only for objects that don't have dependencies of their own, such as value objects:`