Skip to content
Related Articles

Related Articles

Android – Component in Dagger

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 26 May, 2021
Improve Article
Save Article

In order to fully understand the concept of  Component in Dagger, we have to first go through a brief about Dagger itself. Now according to the documentation Dagger is defined as follows : 

‘Manual dependency injection or service locators in an Android app can be problematic depending on the size of your project. You can limit your project’s complexity as it scales up by using Dagger to manage dependencies. Dagger automatically generates code that mimics the code you would otherwise have hand-written.’

Let us analyze what the above statement means.

Imagine the following scenario:  Let us assume we have a class, Bike Class, and two functions, it requires two more classes, namely, Engine and Wheels. Thus we say that Bike Class is dependent on Engine and Wheels and for proper functionality, these dependencies should be implemented. Now in order to instantiate the Bike Class, we also have to create and initialize or precisely, inject the other two classes in the activity’s boilerplate code only. This is depicted as follows :

Instantiating Bike Class without Dagger

Now when the project scales in size there are generally a lot of dependencies among various classes and this above approach can lead to some serious issues and performance bottleneck. This is where Dagger comes into play and it automatically takes care of all the dependencies and instantiation. To have a detailed insight about dagger and dependency injection: Dependency Injection with Dagger 2 in Android

Component in Dagger

Now Component in a Dagger works by creating a graph of all the dependencies in the project so that it can find out where it should get those dependencies when they are needed. In order to implement this, an interface needs to be created and should be annotated with @Component. With this annotation processor, Dagger creates a dependency graph that consists of the relationships between various classes. This allows Dagger to create a container as we would have done with manual dependency injection.

Functions can also be defined inside the @Component interface that returns the instances of the classes needed (Bike Class). @Component informs Dagger to generate a container with all the dependencies required. This is known as Component in Dagger. Let us see the above example in implementation.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Adding Required Dependencies

In order to use dependency injection with the help of dagger, we need to add some dependencies to the Gradle file. Go to Gradle Scripts –> build.gradle(Module: app) and add the following dependencies. After adding both of these dependencies you need to click on Sync Now.


implementation ‘’

annotationProcessor ‘’


Now let us customize some color attributes to enhance the app bar. Go to app > res > values > themes.xml and customize the following color attributes.


<resources xmlns:tools="">
    <!-- Base application theme. -->
    <style name="Theme.GFG" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">#7DE324</item>
        <item name="colorPrimaryVariant">#6F9350</item>
       <!-- Status bar color. -->
       <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>

Step 3: Setting up the activity_main.xml file

In this step, we will be creating the layout of the app. A text box and a button needs to be created where the text view will show some default text and after clicking the button a bike entity will be created and the user will be updated in the text box. Below is the code snippet.


<?xml version="1.0" encoding="utf-8"?>
    <!--Text box to update user -->
        android:text="GFG BIKE"
        app:layout_constraintTop_toTopOf="parent" />
    <!--Button to instantiate the bike entity -->
        android:text="Assemble Bike"
        app:layout_constraintTop_toBottomOf="@+id/bk" />

Step 4: Working with the BikeComponent Interface

In this step, we will create an interface with the annotation @Component which will be responsible for instantiating the bike entity and thus creating the graph of all the dependencies. You may refer to this article to create Interface in Android studio


import dagger.Component;
public interface BikeComponent {
    GFG_Bike getBike();

Step 5: Creating all the necessary classes required for the bike(Bike, Engine, and Wheels)

In this step, we will inject the required classes with annotation @Inject to create the Bike entity. Below is the code snippet for all the files. You may refer to this article to create Class in Android studio Class:


import android.util.Log;
import javax.inject.Inject;
public class GFG_Bike extends Activity {
    GFG_Engine engine;
    GFG_Wheels wheels;
    // Injecting Bike Class
    public GFG_Bike(GFG_Engine engine, GFG_Wheels wheels) {
        this.engine = engine;
        this.wheels = wheels;
        Log.v("Bike_Create", "Assembling Bike");
    // Function to confirm the proper instantiation of GFG_Bike
    public int ride() {
        Log.v("Bike_Ride", "Assembling Successful,Riding it now.");
        return 1;
} Class:


import android.util.Log;
import javax.inject.Inject;
public class GFG_Engine extends Activity {
    // Injecting Engine
    public GFG_Engine() {
        Log.v("Engine", "Collecting engine");
} class:


import android.util.Log;
import javax.inject.Inject;
public class GFG_Wheels extends Activity {
    // Injecting Wheels
    public GFG_Wheels() {
        Log.v("Wheels", "Collecting wheels");

Step 6: Working with the file

In this step, we will instantiate the GFG_Bike. If the step is successful the text view will be updated else an Error Toast will be shown. Below is the code snippet.


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        // Finding the button in the mainactivity layout file
        Button bt = findViewById(;
        bt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // Creating the bikecomponent
                BikeComponent component = DaggerBikeComponent.create();
                GFG_Bike newBike = component.getBike();
                int x = newBike.ride();
                // If successful
                if (x == 1) {
                    TextView bk = findViewById(;
                    bk.setText("Riding Bike");
                // If failed
                    Toast.makeText(MainActivity.this, "Failed to Assemble Bike", Toast.LENGTH_SHORT).show();


Output: On Logcat

Snapshot of Logcat

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!