Dependency Injection in Java
Dependency Injection (DI) is a design pattern in Java used to achieve loose coupling between classes by injecting dependencies from outside instead of creating them internally.
1️⃣ What is Dependency?
If one class uses another class, it is called a dependency.
// Service class
class Engine {
void start() {
System.out.println("Engine Started");
}
}
// Car depends on Engine
class Car {
Engine engine = new Engine();
void drive() {
engine.start();
System.out.println("Car is running");
}
}
Here, Car directly creates Engine object → Tight Coupling ❌
2️⃣ Problem Without Dependency Injection
- Hard to test
- Hard to replace dependency
- Tightly coupled code
- Low flexibility
3️⃣ Dependency Injection Solution
Instead of creating dependency inside class, we inject it from outside.
class Engine {
void start() {
System.out.println("Engine Started");
}
}
class Car {
private Engine engine;
// Constructor Injection
Car(Engine engine) {
this.engine = engine;
}
void drive() {
engine.start();
System.out.println("Car is running");
}
}
// Main
public class Main {
public static void main(String[] args) {
Engine engine = new Engine();
Car car = new Car(engine); // Injecting dependency
car.drive();
}
}
Now Car does not create Engine → Loose Coupling ✅
4️⃣ Types of Dependency Injection
1. Constructor Injection (Recommended)
class Car {
private Engine engine;
Car(Engine engine) {
this.engine = engine;
}
}
✔ Ensures dependency is mandatory
✔ Makes object immutable
2. Setter Injection
class Car {
private Engine engine;
void setEngine(Engine engine) {
this.engine = engine;
}
}
✔ Dependency optional
✔ Can change later
3. Field Injection (Not Recommended)
class Car {
@Autowired
private Engine engine;
}
⚠ Hard to test
⚠ Less control
5️⃣ Dependency Injection using Spring Framework
The Spring Framework provides built-in support for Dependency Injection.
Example using Spring
@Component
class Engine {
public void start() {
System.out.println("Engine Started");
}
}
@Component
class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
public void drive() {
engine.start();
}
}
Spring automatically injects Engine into Car.
6️⃣ Real-World Example
Think of a restaurant:
- Chef → Engine
- Restaurant → Car
- Manager providing chef → Dependency Injection
7️⃣ Advantages of Dependency Injection
- Loose Coupling
- Better Unit Testing
- High Maintainability
- Easy to Replace Implementations
- Improved Code Flexibility
8️⃣ When to Use Dependency Injection?
- Large applications
- Microservices
- Spring Boot applications
- Test-driven development (TDD)
Conclusion
Dependency Injection is a powerful design pattern that improves code quality by reducing tight coupling. Modern Java development (especially Spring Boot) heavily relies on DI.
Mastering Dependency Injection is essential for becoming a professional Java developer.
No comments:
Post a Comment