Learn Dagger2 with simple example


I have read and watched a lot of different Dagger2 tutorials but most of them are too long or hard to understand so I decided to write a new simple and short tutorial for Dagger2, I hope you like it.

Why we need it?

  • Simplifies access to shared instances: It provides a simple way to obtain references to shared instances, for example once we declare in Dagger our singleton instances such as `SharedPrefrences` then we can declare fields with a simple `@Inject` annotation.
  • Easier unit and integration testing: We can easily swap out modules that make network responses and mock out this behavior.

Lest’s start with a simple example

Full source of example is available on my GitHub account.

Add Dagger2 dependencies

First of all we need to add Dagger2 dependencies, Put below code to your module-level build.gradle file.


If you are getting an error like Error:Conflict with dependency ‘com.google.code.findbugs:jsr305’ in project ‘:app’ you should add the following to your main app/build.gradle file.


Two simple class

We have two classes (Vehicle and Motor), Vehicle class needs Motor class to run and MainActivity needs Vehicle class. We will use Dagger2 to provide these instances.



Module class

Module class is responsible for providing objects which can be injected, In this example we want to inject Motor class to Vehicle class and inject Vehicle class to MainActivity so  we should create MyModule to provide these instances.


@Provide annotation: returned object from this method is available for dependency injection.

@Component interface

Dagger2 needs component class to know how should it create instances from our classes.


@Component interface: connection between the provider of object and the objects which express a dependency.

Inject Dependency in Constructor

By adding @Inject annotation, dagger2 can automatically create an instance from that object like our example Motor object in Vehicle class.

Inject dependency in MainClass

Dagger2 can automatically inject dependencies in constructors, but Android components (activities, fragments, etc.) are instantiated by Android framework which makes it difficult to use dependency injection on them, so we should inject them manually like below code:


Little more

Read this article : Dependency Injection with Dagger2
Watch these videos:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.