"Dagger will inject those fields if requested, but will not create new instances" 是什么意思?

What's "Dagger will inject those fields if requested, but will not create new instances" means?

在 Dagger2 的文档中,它说

If your class has @Inject-annotated fields but no @Inject-annotated constructor, Dagger will inject those fields if requested, but will not create new instances. Add a no-argument constructor with the @Inject annotation to indicate that Dagger may create instances as well.

它如何注入字段而不创建新实例?有什么区别?

"if requested" 表示 "if manually injected",即对象是由您或某些框架(想想 Android 和活动对象)创建的,然后您调用 'DaggerMyComponent.inject(myObject);'.

另一方面,当你提供 @Inject 带注释的构造函数时,Dagger 将能够实例化此 class 本身的对象,因此你的 class 可能位于依赖关系图和对象的中间将由 Dagger 自动为您创建。

通常在 Android 中,您只手动注入 android 为您 created/destroyed 的对象(即您不控制它们的生命周期),例如应用程序、活动、服务等.

此外,如果您不小心错过了某些 class' 构造函数上的 @Inject 注释,您也不必担心。如果你的 class 位于图表的中间,Dagger 会发现存在不满足的依赖关系,并且会导致编译失败并出现相应的错误。