Category: java
Constructor Injection in Spring Boot
Published on 22 Apr 2026
Explanation
Constructor Injection in Spring Boot is a
dependency injection technique where
required dependencies are
provided through a class constructor
instead of
field or setter injection.
Code:
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository
userRepository) {
this.userRepository = userRepository;
}
}
Explanation
Spring automatically injects the
required dependency when
the object is created if the dependency
is available as a bean in the
Spring container.
Code:
@Repository
public class UserRepository {
}
Explanation
Constructor injection ensures that
required dependencies are
initialized at object creation time,
making the
class immutable and safer.
Code:
private final UserRepository userRepository;
Explanation
In Spring Boot versions 4.x and later
(and commonly in 2.x+), the
@Autowired annotation
is optional when there is only one
constructor.
Code:
public UserService(
UserRepository userRepository) {
this.userRepository = userRepository;
}
Explanation
Constructor injection improves
testability because dependencies can
be easily passed while writing unit tests.
Code:
UserRepository mockRepo = new UserRepository(); UserService service = new UserService(mockRepo);
Explanation
Constructor injection is recommended
over field injection
because it promotes immutability,
better design, and
easier debugging.
Code:
// Recommended approach in Spring Boot // Prefer constructor injection over @Autowired on fields