Dependency Injection(DI)

Dependency Injection (DI) is a design pattern used in software development to implement Inversion of Control (IoC) between classes and their dependencies. It allows for the decoupling of the creation of a dependency from its usage, making the system more modular, testable, and maintainable.

Key Concepts of Dependency Injection

 
Dependency: A dependency is an object that another object requires to function. For example, if a class A uses an instance of class B, then B is a dependency of A.
 
Injection: Injection refers to the process of providing the dependencies to a class. Instead of the class creating its own dependencies, they are injected from the outside.
 
Example in java :
 
Step 1 : Define the Dependency Interface
Java
				// Repository.java
public interface Repository {
    String getData();
}
			

Step 2 : Provide an Implementation of the Dependency

Java
				public class RepositoryImpl implements Repository {
    @Override
    public String getData() {
        return "Hello from Repository";
    }
}
			

Step 3 : Define the Dependent Class

Java
				// Service.java
public class Service {
    private final Repository repository;

    // Constructor injection
    public Service(Repository repository) {
        this.repository = repository;
    }

    public String fetchData() {
        return repository.getData();
    }
}
			

Step 4 : Main Application

Java
				public class Main {
    public static void main(String[] args) {
        Repository repository = new RepositoryImpl(); // Create the dependency
        Service service = new Service(repository);   // Inject the dependency

        System.out.println(service.fetchData()); // Outputs: Hello from Repository
    }
}
			

Leave a Reply

Your email address will not be published.