Hackforge Academy

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

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community