有人可以很好地解释 Dagger 2 吗?

Can someone provide a good explanation of Dagger 2?

我真的很难理解 Dagger 2 依赖注入系统。

我了解使用 @Inject 注释来告诉 Dagger 我们需要向此处提供某种类型的实例。

但是,我不了解其他组件的各种角色,例如:@Module@Component@Provides 以及它们如何协同工作以提供适当的实例适当的依赖。

有人能简明扼要地解释一下吗?

@Module: Modules are classes whose methods provide dependencies, so we define a class and annotate it with @Module, thus, Dagger will know where to find the dependencies in order to satisfy them when constructing class instances. One important feature of modules is that they have been designed to be partitioned and composed together (for instance we will see that in our apps we can have multiple composed modules).

@Component: Components basically are injectors, let’s say a bridge between @Inject and @Module, which its main responsibility is to put both together. They just give you instances of all the types you defined, for example, we must annotate an interface with @Component and list all the @Modules that will compose that component, and if any of them is missing, we get errors at compile time. All the components are aware of the scope of dependencies it provides through its modules.

@Provide: Inside modules we define methods containing this annotation which tells Dagger how we want to construct and provide those mentioned dependencies.

我建议你阅读这个:

我想这会有助于理解。

您可以在此处找到有用的 Dagger2 示例项目和教程。

Dagger 2 working sample project with MVP

Video tutorial

Practical tutorial

Dagger 2 中使用的注释及其用途

  1. @Inject - 这用于字段、构造函数或方法,表示请求依赖项。这里 Dagger 会构造一个带注解的 class.

    的实例
  2. @Module - 用简单的外行术语来说,就是用于构造对象和提供依赖项的 class。每当 class 被 @Module 注释时,Dagger 就知道在哪里可以找到依赖项。

  3. @Provide - 顾名思义,这家伙的工作就是提供实例。这用于模块 class 中的方法,该方法将 return 对象。

  4. @Component - Inject 和 Module 之间的桥梁。模块 class 不直接向请求 class 提供依赖,它使用组件接口。

我肯定会推荐浏览 ArtKorchagin 提供的链接。