DAGGER 2 Tutorial Part 2: Component, Module and Essential Applications
It will be beneficial to view whiteboard animation of this tutorial in the first place.
Component: @Component is the means to declaratively specify an object graph that Dagger 2 will incarnate during the precompilation process. It is essentially @Component annotated Java interface. Dagger 2 will implement this interface and give us a concrete class implementation. @Component is the bedrock element of Dagger 2. For a complete Dagger 2 application we may do without @Module but @Component is indispensable.
We observe here simplest Dagger 2 Application. Moreover it is complete. @Inject decorated constructor results in immediate object graph residency that our component entertains. CommandRouter has that @Inject decorated contructor therefore this type is object graph resident. Also it is the only type CommandRouterFactory component needs in graph conclusion.
Module: @Module is there for modularization of @Component construction. Remember we are bosses of our enterprise architecture, we like to give commands by emitting Dagger 2 configuration interfaces but we are frugal souls we don’t like to repeat ourselves. @Module is a reusable encapsulation of a number of object providing functions. We declare what we want to @Provide inside @Module boundaries. Sets of @Modules are then declared on top of @Components. @Modules are all about encapsulating object provision declaration and modular graph construction. @Modules are just classes or interfaces with @Module annotation.
We will now observe slightly more complicated Dagger 2 Application. Drip coffee maker will aid us conceiving the subject matter.
Here comes our first class. It is ElectricHeater implementing Heater interface. Coffee is hot therefore we need a heat source. ElectricHeater class has no dependency. This fact deems its residency at the root of our object graph. But its constructor is not @Inject decorated. Therefore Heater type is not in our object graph yet. In order to be so Heater type must be the return type of a @Provides annotated method inside @Module class. Always remember, there are two primary ways of a type’s object graph inclusion. Declaring @Inject decorated class or returning the type from @Provides method of a @Module.
This article needs code snippets as github gists but for the time being it is not possible to add github gists into Linkedin articles. Therefore if you want to read whole article you should follow full Medium version from here.