What is Dependency Injection (DI)?

 

What is Dependency Injection (DI)?


Dependency Injection (DI) is a design pattern used in software development to achieve loose coupling between components by injecting dependencies rather than having components create them internally.

🔹 Key Idea:

Instead of a class creating its own dependencies, they are provided (injected) from the outside. This makes the code more flexible, testable, and maintainable.


🔹 Example Without Dependency Injection (Tightly Coupled)

class Service {

    void serve() {

        System.out.println("Service is running...");

    }

}


class Client {

    private Service service;


    public Client() {

        this.service = new Service(); // Tightly coupled

    }


    void doWork() {

        service.serve();

    }

}


public class Main {

    public static void main(String[] args) {

        Client client = new Client();

        client.doWork();

    }

}


🔴 Problem:

  • The Client class directly depends on Service, making it difficult to modify or test.
🔹 Example With Dependency Injection (Loosely Coupled)


class Service {
    void serve() {
        System.out.println("Service is running...");
    }
}

// Injecting dependency via constructor
class Client {
    private Service service;

    public Client(Service service) { // Dependency is injected
        this.service = service;
    }

    void doWork() {
        service.serve();
    }
}

public class Main {
    public static void main(String[] args) {
        Service service = new Service(); // Creating the dependency
        Client client = new Client(service); // Injecting the dependency
        client.doWork();
    }
}

Benefits:

  • Loose Coupling: Client doesn’t depend on the exact implementation of Service.
  • Easier Testing: We can easily swap Service with a mock object for testing.
  • More Flexible: We can inject different implementations of Service.

🔹 Types of Dependency Injection

  1. Constructor Injection

    • Injects dependency via the constructor. (Preferred approach for immutability.)
class Client {
    private Service service;
    public Client(Service service) {
        this.service = service;
    }
}

2.

Setter Injection

  • Injects dependency via a setter method.
class Client {
    private Service service;
    public void setService(Service service) {
        this.service = service;
    }
}

Interface Injection (Less Common)

  • Dependency is injected using an interface.



Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence