Most beginners get confused when they hear this line in Spring Boot:
“Spring automatically injects dependencies using the IoC container.”
Sounds complex, right?
You write a simple Java class, add @Autowired, and suddenly everything works.
No object creation, no new keyword, no manual wiring.
But the real question is
What is dependency injection in Spring Boot, and why does every modern Java backend rely on it?
If you don’t understand this concept, Spring Boot will always feel like magic.
In this guide, I’ll explain dependency injection in plain English with real examples, simple analogies, and practical Spring Boot code so you can actually understand and use it in real projects.
What is Dependency Injection in Spring Boot?
Dependency Injection in Spring Boot is a design pattern where the Spring framework automatically provides the required objects (dependencies) to a class instead of the class creating them manually.
In simple terms:
- A class needs another class to work
- Spring creates that object
- Spring injects it automatically
- You focus only on business logic
This is managed by the IoC (Inversion of Control) Container.
Detailed Explanation
Let’s understand this step by step.
Without Dependency Injection
private UserRepository userRepository = new UserRepository();
}
Here:
- UserService creates UserRepository
- Code is tightly coupled
- Hard to test
- Hard to change
- Not flexible
If you want to replace UserRepository, you must change the code.
That’s a problem.
With Dependency Injection
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Now:
- UserService does not create UserRepository
- Spring provides it
- Code becomes flexible
- Easy to test
- Easy to manage
This is dependency injection in Java in action.
Download Dependency Injection Spring Boot Cheat Sheet (PDF): dependency_injection_spring_boot_cheatsheet
Real-Life Analogy
Imagine you run a restaurant.
Without Dependency Injection
You cook food, serve food, clean tables, manage billing, and buy vegetables.
You do everything.
Result:
- Slow work
- Stress
- Poor efficiency
With Dependency Injection
You hire:
- Chef
- Cleaner
- Manager
- Supplier
They provide services to you.
You focus on running the restaurant.
Spring Boot works the same way.
It provides required objects so your class can focus on business logic.
Simple.
Types of Dependency Injection in Spring Boot

There are 3 main types:
- Constructor Injection
- Setter Injection
- Field Injection
Let’s understand each.
1. Constructor Injection Spring Boot
This is the most recommended approach.
Example
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Spring automatically injects UserRepository.
Why it is best
- Immutable
- Easy testing
- No null values
- Clean code
- Recommended by Spring team
2. Setter Injection
Used when dependency is optional.
Example
public class UserService {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Use case
Optional dependencies.
3. Field Injection
Most beginners use this.
public class UserService {@Autowired
private UserRepository userRepository;
}
Easy but not recommended
Why?
- Hard to test
- Reflection based
- Not clean
- Hidden dependencies
Spring Boot DI Example
Repository
public class UserRepository { public String getUser() {
return “User Data”;
}
}
Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String getUserData() {
return userRepository.getUser();
}
}
Controller
public class UserController {
private final UserService userService; public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping(“/user”)
public String getUser() {
return userService.getUserData();
}
}
Output
Spring injects everything automatically.
No manual object creation.
Comparison Table
| Feature | Constructor Injection | Setter Injection | Field Injection |
|---|---|---|---|
| Recommended | ✅ Yes | ⚠️ Sometimes | ❌ No |
| Testable | ✅ Easy | ✅ Medium | ❌ Hard |
| Immutability | ✅ Yes | ❌ No | ❌ No |
| Null Safety | ✅ High | ⚠️ Medium | ❌ Low |
| Readability | ✅ Clean | ⚠️ OK | ❌ Poor |
| Spring Recommendation | ✅ Strong | ⚠️ Limited | ❌ Avoid |
When to Use What
Use Constructor Injection when
- Dependency is required
- Service layer
- Controller layer
- Production code
- Clean architecture
Best choice in 2026.
Use Setter Injection when
- Dependency is optional
- Configuration based
- Dynamic behavior
Avoid Field Injection when
- Writing production code
- Writing scalable apps
- Writing testable apps
Only okay for small demos.
Common Mistakes Developers Make
1. Using Field Injection Everywhere
Many beginners write:
private UserRepository userRepository;
This creates hidden dependencies.
Bad practice.
2. Creating Objects Manually
This breaks Spring IoC.
Always let Spring manage objects.
3. Not Using Final in Constructor Injection
Wrong: private UserRepository repo;
Correct: private final UserRepository repo;
Improves safety.
Best Practices (2026)

1. Always Use Constructor Injection
The spring team recommends this.
Cleaner and safer.
2. Use Final Dependencies
Prevents accidental changes.
3. Keep Services Stateless
Avoid storing data in services.
Use them for logic only.
4. Let Spring Manage Beans
Use:
@Service@Repository@Component@Controller
Avoid manual object creation.
Practice Dependency Injection with a Mini Project
Build this
User Management API
Features:
- Controller
- Service
- Repository
- Constructor Injection
Steps
- Create Spring Boot project
- Create UserRepository
- Create UserService
- Inject dependency
- Create API
- Run application
Output
GET /users
Returns data.
You can create this project using Spring Boot Initializr in 5 minutes.
Pro Tip
If you use Spring Boot 3+, you don’t need @Autowired on constructor.
Spring automatically injects dependencies.
Example:
this.userRepository = userRepository;
}
Clean and modern.
Interview Questions
1. What is dependency injection in Spring Boot?
2. What is an IoC container?
3. Constructor vs Field Injection?
4. Why is constructor injection better?
5. Can we use multiple constructors?
6. What is @Autowired?
FAQs (Frequently Asked Questions)
1. What is dependency injection in Spring Boot in simple terms?
Dependency injection in Spring Boot is a mechanism where the Spring framework provides required objects (dependencies) to a class instead of the class creating them manually. The Spring IoC container manages object creation, configuration, and lifecycle using configuration metadata such as annotations or Java code. This reduces tight coupling and makes applications easier to test and maintain. In simple terms, classes declare what they need, and Spring supplies those dependencies automatically.
Source: Spring Framework Documentation
2. Why is dependency injection used in Spring Boot?
Dependency injection is used in Spring Boot to reduce tight coupling between components and improve code flexibility and testability. The Spring container manages dependencies so classes do not need to locate or create other objects themselves. This allows developers to replace implementations, use mock objects in testing, and maintain cleaner architecture. It also simplifies configuration and lifecycle management of application components.
Source: Spring Framework Documentation
3. What is the IoC container in Spring Boot?
The IoC (Inversion of Control) container is the core component of the Spring Framework that manages beans and their dependencies. It creates objects, injects dependencies, and handles their lifecycle based on configuration metadata like annotations, XML, or Java configuration. The ApplicationContext interface represents this container and is responsible for assembling and managing all application components. This central management ensures consistent object creation and dependency handling across the application.
Source: Spring Documentation
4. Is @Autowired required for dependency injection in Spring Boot?
@Autowired is commonly used to inject dependencies, but it is not always required in modern Spring Boot versions. When a class has a single constructor, Spring automatically performs constructor-based dependency injection without needing @Autowired. This behavior is part of Spring’s annotation-based configuration system and simplifies dependency wiring. However, @Autowired may still be used for clarity or when multiple constructors exist.
Source: Spring Framework Documentation
5. Which type of dependency injection is recommended in Spring Boot?
Constructor injection is generally recommended in Spring Boot because it makes dependencies explicit and improves testability. The Spring documentation highlights constructor arguments and property-based injection as core dependency injection mechanisms managed by the container. Constructor injection also helps ensure that required dependencies are provided at object creation time, reducing configuration errors. Field injection is supported but less preferred in production environments.
Source: Spring Framework Documentation
Quick Summary
- Dependency Injection provides objects automatically
- Managed by IoC container
- Constructor injection is best
- Setter injection is optional
- Field injection should be avoided
- Spring Boot handles everything automatically
If you’re new to Spring, first read What is Spring Boot in Java – Beginner Guide.
Conclusion
Now you clearly understand what is dependency injection in Spring Boot and why it is one of the most important concepts in modern Java backend development.
If you master dependency injection:
- Your Spring Boot code becomes cleaner
- Your applications become scalable
- Your interviews become easier
- Your projects become production-ready
Next Step
If you’re learning Spring Boot, the best move now is:
- Build a small CRUD project
- Use constructor injection
- Create service and repository layers
- Practice real dependency injection
Want a real-world example? Build the IPL Player Stats App using Spring Boot.
Want more beginner-friendly Spring Boot guides like this?
Explore more tutorials on GroWithMoney and start building real-world Java backend projects today.
Discover more from GroWithMoney
Subscribe to get the latest posts sent to your email.
