DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Why I Started Using Dependency Injection in Python
  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Understanding the Dependency Injection Lifecycle: Singleton, Scoped, and Transient With Detailed Examples
  • Dependency Injection

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Automatic Code Transformation With OpenRewrite
  • How to Convert XLS to XLSX in Java
  • Integrating Security as Code: A Necessity for DevSecOps
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Dagger 2 Tutorial: Dependency Injection Made Easy

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.

By 
Jose Manuel García Maestre user avatar
Jose Manuel García Maestre
·
Jul. 13, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
55.1K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Dependency injection

Published at DZone with permission of Jose Manuel García Maestre, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why I Started Using Dependency Injection in Python
  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Understanding the Dependency Injection Lifecycle: Singleton, Scoped, and Transient With Detailed Examples
  • Dependency Injection

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!