gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:04:09 28 4
gpt4 key购买 nike

在 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.

它如何注入(inject)字段但不创建新实例?有什么区别?

最佳答案

“if requested”表示“如果手动注入(inject)”,即对象由您或某些框架(想想 Android 和 Activities 对象)创建,然后您调用“DaggerMyComponent.inject(myObject);”。

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

通常在 Android 中,您只手动注入(inject)由 android 为您创建/销毁的对象(即您不控制它们的生命周期),例如应用程序、 Activity 、服务等。

此外,如果您不小心错过了某些类的构造函数上的 @Inject 注释,您也不必担心。如果你的类在图的中间,Dagger 会发现有不满足的依赖项,并且会导致编译失败并出现适当的错误。

关于android - "Dagger will inject those fields if requested, but will not create new instances"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33591948/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com