← All tutorials

GoCareerGo Tutorials

Spring Boot Tutorial

Auto-configuration, REST APIs, JPA, AOP, caching, microservices and Spring Cloud.

Dependency Injection in Spring Boot

Instead of a class creating its own dependencies, Spring 'injects' them — making code loosely coupled and easy to test.

@Service
public class OrderService {
    private final PaymentService paymentService;

    // Constructor injection — the recommended approach
    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}
  • Constructor injection — preferred; makes dependencies explicit and final
  • Field injection (@Autowired on a field) — concise but harder to unit test
  • Setter injection — used for optional dependencies
Tip

Always recommend constructor injection when asked — it's the current best practice and enables immutability.