Constructor Injection and Circular Dependencies
Prefer constructor injection for testability, detect circular dependencies, and break them with @Lazy.
Three Injection Types
Spring supports constructor injection (recommended), field injection (@Autowired on a field), and setter injection. Constructor injection is preferred for testability and immutability.
Constructor Injection
Declare dependencies as constructor parameters. Spring injects them automatically. If there is only one constructor, @Autowired is optional (Spring Boot 2.1+).
@Service
public class OrderService {
private final OrderRepository repo;
private final EmailService email;
// @Autowired is optional when there is only one constructor
public OrderService(OrderRepository repo, EmailService email) {
this.repo = repo;
this.email = email;
}
}All lessons in this course
- Auto-Configuration and Spring Boot Starters
- Application Properties and Profiles
- Bean Wiring: @Component, @Service, @Repository
- Constructor Injection and Circular Dependencies