Guice 如何在没有 @Inject 注释的构造函数的情况下注入类?
我试图了解 DI 在我们的代码库 (Kotlin) 中的使用方式。我们使用 google guice 进行依赖注入。
这是一个示例类:
class ServiceClass @Inject construct(
private val depA: DepA,
private val depB: DepB
) { ........ }
在模块类中:
@Provides
fun provideDepA(): DepA {
//constructs DepA object and returns it
}
DepB 类:
class DepB { .... }
据我所知,对于用 @Inject
注释的变量,Google Guice 将使用模块类来解决这些依赖关系。因此,DepA
对象的注入方式是有意义的。
但是 DepB
呢?我们如何能够在不指定任何地方的情况下注入 DepB?
I'm trying to understand how DI is used in our codebase (Kotlin). We are using google guice for dependency injection.
Here is a sample class:
class ServiceClass @Inject construct(
private val depA: DepA,
private val depB: DepB
) { ........ }
In Module class:
@Provides
fun provideDepA(): DepA {
//constructs DepA object and returns it
}
DepB class:
class DepB { .... }
As far as I know for the variables annotated with @Inject
, Google Guice will look to resolve those dependencies using module class. So it makes sense how DepA
object is injected.
But what about DepB
? How are we able to inject DepB without specifying it anywhere?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
未在模块中声明的 Guice 绑定称为即时绑定,默认情况下,Guice 愿意调用带有零参数的构造函数:
如果您没有所需的显式绑定,并且您有公共无参数构造函数,Guice 将调用它,就像您用
@Inject
标记它一样。这与 Dagger 形成鲜明对比,Dagger 仅调用@Inject
-注释的构造函数:在 Guice 和 Dagger 中,您可以使用
@Provides
方法自行构造对象,在 Guice 中,您还可以使用模块来 使用参数显式绑定到构造函数,但不使用@Inject
构造函数。Guice bindings that are not declared in modules are known as Just-in-time Bindings, and by default Guice is willing to call constructors that take zero arguments:
If you haven't required explicit bindings and you have a public no-arg constructor, Guice will call it as if you had marked it with
@Inject
. This is in contrast to Dagger, which will only call@Inject
-annotated constructors:In both Guice and Dagger you can construct the objects yourself in
@Provides
methods, and in Guice you can also use a Module to explicitly bind to a constructor with arguments and without an@Inject
constructor.