简体   繁体   English

Dagger2中模块和组件之间的区别

[英]Difference between module and component in Dagger2

Can somebody please tell me what is the basic difference between the module and component in Dagger2 ? 有人可以告诉我Dagger2 modulecomponent之间的基本区别是什么?

If possible, please tell with some examples, so that it is easily understood. 如果可能的话,请告诉我们一些例子,以便于理解。

We can group dependencies in a module for example Network module can provide HTTPClient Retrofit,GSON, HTTP Logger etc. 我们可以在模块中对依赖关系进行分组,例如,Network模块可以提供HTTPClient Retrofit,GSON,HTTP Logger等。

similarly we can have Database Module, Application Module, or any feature specific module. 类似地,我们可以拥有数据库模块,应用程序模块或任何特定功能模块。

Component is a bridge between Module(provider) and Activity/Fragment(Consumer) and it can have more than one module. 组件是Module(提供者)和Activity / Fragment(Consumer)之间的桥梁,它可以有多个模块。

Inside Activity/Fragment we can get these dependencies by defining like below 在Activity / Fragment中,我们可以通过定义如下来获得这些依赖

@Inject 
Gson gson;   

these dependency will be fulfilled as soon as you inject the component(in this case network component which contains network module which contains Gson Provider method) 注入组件后,这些依赖关系将被实现(在这种情况下,网络组件包含包含Gson Provider方法的网络模块)

getNetworkComponent().inject(MyActivity.this/MyFragment.this)

here is a very good tutorial with simple example https://code.tutsplus.com/tutorials/dependency-injection-with-dagger-2-on-android--cms-23345 这是一个非常好的教程,简单的例子 https://code.tutsplus.com/tutorials/dependency-injection-with-dagger-2-on-android--cms-23345

In other words 换一种说法

A dependency consumer asks for the dependency(Object) from a dependency provider through a connector. 依赖性使用者通过连接器向依赖性提供者请求依赖性(Object)。

Dependency provider: 依赖提供者:

Classes annotated with @Module are responsible for providing objects which can be injected. 使用@Module注释的类负责提供可以注入的对象。 Such classes define methods annotated with @Provides. 这些类定义了使用@Provides注释的方法。 The returned objects from these methods are available for dependency injection. 这些方法返回的对象可用于依赖注入。

Dependency consumer: 依赖性消费者:

The @Inject annotation is used to define a dependency. @Inject注释用于定义依赖项。

Connecting consumer and producer: 连接消费者和生产者:

A @Component annotated interface defines the connection between the provider of objects (modules) and the objects which express a dependency. @Component带注释的接口定义对象(模块)提供者与表示依赖关系的对象之间的连接。 The class for this connection is generated by the Dagger. 此连接的类由Dagger生成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM