Learn about Spring Boot Dependency Injection (DI) in Spring Boot with this detailed guide. Explore constructor, setter, and field injection, scopes, and more. Includes common interview questions to help you prepare.
Imagine you’re playing with toy blocks, and you want to build a castle. But instead of building each part of the castle yourself, your friend gives you the pieces and helps you put them together. You don’t have to go and find every single piece; your friend already has it ready for you.
In the world of computer programs, Spring Boot Dependency Injection is like having a helpful friend who gives your program the pieces it needs (like tools or information) without you having to find them yourself. It makes it easier to build things because you don’t have to worry about getting every little part – it’s all handed to you when you need it.
So, just like your friend gives you the blocks to build your castle, Spring Boot Dependency Injection gives your program the pieces it needs to work properly!

Table of Contents
Introduction to Spring Boot Dependency Injection (DI)
Spring Boot Dependency Injection (DI) is one of the fundamental concepts in Spring Framework. It allows you to inject dependencies into an object rather than creating the object directly. This promotes loose coupling, which makes your application easier to test and maintain.
In Spring Boot, DI is used extensively to manage your beans and simplify your application’s configuration. Let’s dive deeper into how DI works in Spring Boot, explore different types of DI, and discuss how to use them effectively in your applications.
How Spring Boot Dependency Injection Works in Spring Boot
Spring Boot uses Inversion of Control (IoC) to manage the lifecycle and configuration of beans in the application. By using DI, Spring handles the creation and wiring of beans (objects) at runtime, ensuring that dependencies are properly injected.
The DI process involves three key elements:
- Bean: A Spring-managed object (usually a service or a repository).
- Container: The Spring context (e.g., ApplicationContext) which contains the beans.
- Spring Boot Dependency Injection: The process by which Spring Boot automatically injects dependencies into a class.
Types of Spring Boot Dependency Injection in Spring Boot
Spring Boot supports three types of DI:
- Constructor Injection
- Setter Injection
- Field Injection
1. Constructor Injection
Constructor Injection is the most recommended way of performing DI in Spring. It ensures that all required dependencies are provided when an object is created, thus guaranteeing that the object is in a valid state.
Example:
javaCopy codepackage com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
// Constructor Injection
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void performService() {
userRepository.save();
}
}
Explanation:
@Service
: This annotation marks the class as a Spring-managed bean.- Constructor Injection: The
UserService
class requires an instance ofUserRepository
. Spring automatically injects the dependency when creatingUserService
.
2. Setter Injection
Setter Injection allows Spring to inject dependencies via setter methods. This is useful when the dependency is optional or may change after the object’s initialization.
Example:
javaCopy codepackage com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private UserRepository userRepository;
// Setter Injection
@Autowired
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void performService() {
userRepository.save();
}
}
Explanation:
@Autowired
: This annotation tells Spring to inject the dependency into the setter method.- Setter Injection: The dependency is injected after the
UserService
object is created.
3. Field Injection
Field Injection is the simplest form of DI, where Spring directly injects dependencies into the fields of a class.
Example:
javaCopy codepackage com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void performService() {
userRepository.save();
}
}
Explanation:
@Autowired
: The annotation is applied directly to the field, allowing Spring to inject the dependency automatically.
Note: Field Injection is often criticized for making testing difficult and for not enforcing immutability, but it can be convenient for smaller applications.
Advantages of Spring Boot Dependency Injection in Spring Boot
- Loose Coupling: DI decouples object creation and dependency resolution, making components easier to test and modify.
- Easier Testing: By injecting mock or stub dependencies, unit tests become easier to write and maintain.
- Better Maintainability: DI simplifies the configuration of objects and their dependencies, which makes the codebase more maintainable.
- Flexibility: The Spring IoC container allows you to change implementations easily by swapping dependencies without altering the core business logic.
Spring Boot Dependency Injection and Scopes
Spring beans can have different scopes that determine their lifecycle and visibility. These scopes are controlled by annotations:
- Singleton (Default Scope): Only one instance of the bean is created in the container. Most beans are singletons by default in Spring Boot.
- Annotation:
@Scope("singleton")
- Annotation:
- Prototype: A new instance of the bean is created each time it is requested.
- Annotation:
@Scope("prototype")
- Annotation:
- Request: A bean is created for each HTTP request.
- Annotation:
@Scope("request")
- Annotation:
- Session: A bean is created for each HTTP session.
- Annotation:
@Scope("session")
- Annotation:
- Application: A bean is created once per servlet context.
Example of Singleton and Prototype Scopes:
javaCopy code@Service
@Scope("singleton") // Singleton Scope
public class SingletonService { ... }
@Service
@Scope("prototype") // Prototype Scope
public class PrototypeService { ... }
Spring Boot Spring Boot Dependency Injection with Qualifiers
In some cases, you may have multiple beans of the same type, and you need to specify which one should be injected. This can be done using the @Qualifier
annotation.
Example:
javaCopy codepackage com.example.demo.service;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(@Qualifier("mySQLRepository") UserRepository userRepository) {
this.userRepository = userRepository;
}
}
Explanation:
@Qualifier("mySQLRepository")
: This annotation specifies which bean to inject if there are multiple beans of the same type.
Spring Boot Dependency Injection Interview Questions
To prepare for interviews, here are some common questions related to Spring Boot Dependency Injection in Spring Boot:
- What is Spring Boot Dependency Injection, and why is it used in Spring Boot?
- DI is a design pattern that allows an object to receive its dependencies from an external source rather than creating them internally. It is used to achieve loose coupling and easier testing.
- Explain the difference between constructor injection, setter injection, and field injection.
- Constructor Injection: Dependencies are injected through the constructor (recommended).
- Setter Injection: Dependencies are injected via setter methods (used for optional dependencies).
- Field Injection: Dependencies are injected directly into fields (least preferred due to potential testing challenges).
- What is the default scope of a Spring bean?
- The default scope of a Spring bean is singleton, meaning only one instance is created for the entire application context.
- How do you handle multiple beans of the same type in Spring Boot?
- You can use the
@Qualifier
annotation to specify which bean to inject when there are multiple beans of the same type.
- You can use the
- What is the role of
@Autowired
in Spring Boot?@Autowired
is used to mark a constructor, setter, or field to be automatically injected with a bean from the Spring context.
- Explain the difference between
@Scope("singleton")
and@Scope("prototype")
.singleton
: A single instance of the bean is shared across the entire application context.prototype
: A new instance of the bean is created every time it is requested.
- What are the advantages of using Spring Boot Dependency Injection in Spring Boot?
- Loose coupling, easier testing, flexibility, better maintainability, and separation of concerns.