简体   繁体   中英

Difference between module and component in Dagger2

Can somebody please tell me what is the basic difference between the module and component in Dagger2 ?

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.

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.

Inside Activity/Fragment we can get these dependencies by defining like below

@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)

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

In other words

A dependency consumer asks for the dependency(Object) from a dependency provider through a connector.

Dependency provider:

Classes annotated with @Module are responsible for providing objects which can be injected. Such classes define methods annotated with @Provides. The returned objects from these methods are available for dependency injection.

Dependency consumer:

The @Inject annotation is used to define a dependency.

Connecting consumer and producer:

A @Component annotated interface defines the connection between the provider of objects (modules) and the objects which express a dependency. The class for this connection is generated by the Dagger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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