Dependency Injection Explained with Spring
Dependency Injection Explained with Spring Framework
🔰 What is Dependency Injection (DI)?
Dependency Injection is a design pattern used to remove tight coupling between objects.
It helps make code easier to test, maintain, and scale.
In simple words:
👉 Instead of a class creating its own dependencies, they are given (injected) to it from outside.
🎯 Why Use Dependency Injection?
Without DI:
With DI:
✅ Loose coupling
✅ Easy to test
✅ Better flexibility
✅ Supports modular code
🧰 What is Spring Framework?
Spring is a powerful Java framework for building web apps and enterprise-level software.
It provides built-in support for Dependency Injection using:
-
XML configuration
-
Annotations
-
Java-based configuration
🔧 Types of Dependency Injection in Spring
Spring supports:
1. Constructor Injection
Dependencies are passed through the class constructor.
2. Setter Injection
Dependencies are injected via public setter methods.
3. Field Injection (less recommended)
Dependencies are directly injected into class fields using @Autowired
.
📦 Example: Constructor Injection with Spring
Step 1: Create the Dependency Class
Step 2: Create the Dependent Class
Step 3: Create Spring Configuration (Java-based)
Step 4: Create the Main Class
✅ Output:
📝 Setter Injection Example
In AppConfig
:
🧠 When to Use Which?
Type | Use When... |
---|---|
Constructor Injection | Dependency is required, and should not change |
Setter Injection | Dependency is optional or may change later |
Field Injection | Avoid in large projects (hard to test and manage) |
🛠 Using Annotations for DI
Spring provides easy annotations for DI.
In MainApp
:
🔄 DI vs Traditional Programming
Feature | Without DI | With DI (Spring) |
---|---|---|
Coupling | Tight | Loose |
Testing | Hard (need real objects) | Easy (can use mock objects) |
Flexibility | Low | High |
Maintenance | More effort | Easier |
✅ Benefits of Using Dependency Injection
-
Separation of concerns
-
Easier unit testing
-
Reusable and flexible components
-
Centralized configuration
-
Reduces boilerplate code with Spring
💡 Real-World Use Case
Imagine a web application with:
-
A
UserService
that needs aUserRepository
-
A
UserController
that needs theUserService
Instead of creating objects manually:
Spring does all this for you automatically using DI.
🚀 Summary
Dependency Injection is a powerful way to build flexible and testable applications.
✅ Helps reduce tight coupling
✅ Makes testing easier
✅ Spring handles it automatically using annotations or config
✅ Use constructor injection for required dependencies
✅ Use setter injection for optional ones
Final Thought
If you want to build scalable, clean Java apps — Dependency Injection with Spring is a must-learn skill.
Comments
Post a Comment