Dagger:需要帮助理解

Dagger: need help in understanding

我对匕首的工作方式有一些误解:

  1. 满足依赖只有两种方式:@Provide方法returns实例,或者class应该有@Singleton注解, 那正确吗?在后一种情况下,class 构造函数必须具有 @Inject 注释吗?

  2. 如我所见,ObjectGraph 生成所有注入内容。据说,应该调用它的 inject(T instance) 来注入字段。但是,我可以只用 @Inject 注释我的字段,然后就可以了(字段的 class 是 @Singletone)。不需要 ObjectGraph 来满足这种依赖关系,对吗?

  3. @Module中的injects{}呢,具体给出了什么?请提供一个当您保留所有可注射 classes 列表时的好处示例。

  1. 是的,有两种方法:@Provide 模块中的方法和 @Singleton class 在构造函数中使用 @Inject 方法。

Must the class constructor have @Inject annotation in the latter case?

是的,否则 Dagger 不会创建对象。

  1. 我认为 @Singleton 字段注入行不通。因为 @Singleton 在 class 使用构造函数注入意味着 Dagger 负责保留此 class 的一个实例。如果满足所有依赖项,它可以使用构造函数注入创建此 class。但是,@Singleton 和字段注入对我来说似乎是滥用,因为现在保留这个 class 的单个实例是用户的责任。 Dagger 无法实例化此对象本身。
    您确定此配置可以编译并运行吗?如果是检查 @Inject 字段,根据我的理解,它们应该为空。

  2. injects={}@Module returns 组 class 中传递给 ObjectGraph.inject(T class)ObjectGraph.get(Class<T> class)。引用 documentation:

    It is an error to call ObjectGraph.get(java.lang.Class) or ObjectGraph.inject(T) with a type that isn't listed in the injects set for any of the object graph's modules. Making such a call will trigger an IllegalArgumentException at runtime.

这个集合帮助 Dagger 执行静态分析以检测错误和未满足的依赖关系。
您可以在 this thread.

中找到一些示例