Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Dagger 2 Tutorial: Dependency Injection Made Easy

DZone's Guide to

Dagger 2 Tutorial: Dependency Injection Made Easy

Need help with dependencies and injections in Java? Check out this tutorial on how to use dependency injections in Dagger 2.

Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Dependency injection is a difficult concept to understand. If you are tired of seeing dependency, injection, dagger, or even random words in Java, then, you have found the right article for you!

First, let’s define dependency and injections in Java.

Dependency and Injection

As the words indicate, dependency means to depend, and injection means to inject something into something else. Easy, right? When you combine these two things together, it becomes a "dependency injection," meaning that you can now inject dependencies.

But, what does it mean in Java? What are dependencies in code? Let’s do a class diagram:

Image title

Here, we can see all the dependencies, and we can review the diagram if we have any doubt during coding.

In the diagram, we have a class Body  that depends on a class Blood . Just like in real life, Body  will have Blood  as a member inside of its class (Body depends on Blood). In addition, we can inject the blood  into the body  using an injection. Of course, we could create a factory inside Body to create Blood,  but this would create boilerplate code. It is better that we just inject it through a dependency injection framework — this is where Dagger 2 comes in.

Let’s continue our discussion on how we can inject the Body  into a class by using Dagger.

Dagger and Dependencies

Dagger is a dependency injection framework for Android, and, here, we see how to use and configure it.

Firstly, we need to add Dagger to our project using Gradle dependencies:

dependencies {
    //Dagger dependencies
    implementation 'com.google.dagger:dagger:2.15'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.15'
}


Dagger injects the class using the annotation  @inject . It can be used in a constructor:

package com.ricston.injectionexample.domain;

import com.ricston.injectionexample.domain.com.ricston.injectionexample.domain.blood.Blood;

import javax.inject.Inject;

public class Body {

    @Inject
    public Body(){}
}


In this way, Dagger injects the Body  class into another class when needed by the injection. For example, let’s say that we have a class Person that needs the injection of a Body . We can do this:

public class Person{

  Body body;

  @Inject
  public Person(Body body){
    this.body = body;
  }

}


Since the Body   is not a singleton, Dagger creates a new Body  object every time that a Person  is created by Dagger. Of course, every person has a different body, so this is okay.

Now, let’s inject Blood into the Body:

public class Body {

    @Inject
    Blood blood;

    @Inject
    public Body(){}

    public Blood getBlood() {
        return blood;
    }

    public void setBlood(Blood blood) {
        this.blood = blood;
    }
}


Now, let’s create the class for Blood:

public abstract class Blood {

    public abstract String getKindOfBlood();
}


This one is an abstract class and its subclass extends Blood . It will get the type of Blood as a string. Every type of blood returns a different letter. You can review these types in the GitHub project at the end of the article.

Okay, you may think, "Good — we have everything set. The Blood  will be injected into the Body, but… how?" We have 4 types of Blood: A, B, AB and O. Blood is just an interface. How does Dagger know which Blood to inject? The answer is that it doesn’t know. This will not work; we need some kind of injection module that injects the blood type we need. Therefore, to solve this problem, Dagger introduced a new concept: the Module.

Dagger Modules

A module is a class that injects concrete classes for an interface. It allows different modules to inject different kinds of concrete implementations into our code. In addition, we can plug-out and plug-in different modules by code. In our case, we use a module called RandomInjectionModule that injects random Bloo  into the Body. It sounds scary, but it is just a programming example — nobody will die! Notice that we don’t need a module if we don’t need to inject an interface.

Let’s implement a module. We will use the @module  in a class and @provides  in a method. It’s a better practice to suffix the class with the module and method with the prefix, 'provide' , as shown below:

@Module
public class RandomInjectionModule {

    private static Blood blood;

    public RandomInjectionModule() {
    }

    @Provides
    static Blood provideBlood(){

        if(blood != null) {
            return blood;
        }

        Random rnd = new Random();
        int rndNumber = rnd.nextInt(3);

        switch (rndNumber){
            case 0: blood = new A_Blood(); break;
            case 1: blood = new B_Blood(); break;
            case 2: blood = new AB_Blood(); break;
            case 4: blood = new O_Blood(); break;
            default: blood = new A_Blood();
        }
        return blood;
    }
}


As you can see, a Blood instance is returned as a concrete class. In fact, it will always return the same instance, since it was marked as static.

Now, we need to use the module in our code. To do that, Dagger introduces another new concept: Component .

Dagger Components

A component is an interface that specifies which modules to use and what objects to return for our code. For example, we are in our main method in Java, and we have a Doctor component that uses the random injection module to inject blood:

@Component( modules = RandomInjectionModule.class )
public interface Doctor {
    Body injectBlood();
}


In the above code, we return a Body using the RandomInjectionModule. It means that a random blood is injected into the Body  automatically by the dependency injection framework that we specified using the @injection  in the Body. If we returned a Person  using the RandomInjectionModule,  then, a random Blood and Body  will be injected as well.

Now, let’s use our component in our code. Dagger 2 generates a class with the same name as our class, prefixed with ‘Dagger’ when our project is compiled. In our case, it’s called DaggerDoctor.   It has different methods to set different instances of our modules. In our case, all dependencies can be constructed without the user creating a dependency instance. The DaggerDoctor  component has a create() method that instantiates our module and injects our classes automatically:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Body body = createBody();

        TextView bloodTV = findViewById(R.id.blood_tv);

        bloodTV.setText("Kind of Blood: " + body.getBlood().getKindOfBlood());
    }

    private Body createBody() {
        Doctor doctor = DaggerDoctor.create();
        return doctor.injectBlood();
    }
}


First, we created an instance of our Doctor interface using DaggerDoctor  through our create()  method, which instantiates our module and injections automatically. Then, we can use our Body as normal and get the blood to print out the blood class that was injected.

Singleton

If you want to use singleton to always inject the same instance, we could have used  @singleton  tag in a class, the  @provide  method for the case of interfaces, and @singleton  in the component as a scope.

In order to use singleton, you must instantiate the component project once. Perhaps, you might want to have a static method to always retrieve the same component for any class that wants to use it. You can find several examples, like singleton, in different branches of my GitHub project.

Conclusion

Dagger 2 can save you a lot of code and time, while also helping to apply the best practices to your projects. For more information, check out the official guide.

I hope that this tutorial has been useful to you. Please don’t hesitate to add any queries or suggestions in the comments below.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
dependency injection ,dagger 2 ,java ,tutorial ,body ,injections

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}