0Pricing
Spring Boot 4 Microservices & REST APIs · Lesson

Constructor vs Field Injection

Choose the right injection style.

Three Ways to Inject

Spring can inject dependencies three ways: through the constructor, into fields, or via setters. They all work, but they are not equal in quality.

The Spring team and community strongly recommend constructor injection. This lesson explains why.

Field Injection

Field injection places @Autowired directly on a field. It looks compact, but hides the dependency and complicates testing.

@Service
public class OrderService {
    @Autowired
    private OrderRepository repo;
    @Autowired
    private PricingService pricing;
}

All lessons in this course

  1. The Spring IoC Container
  2. Constructor vs Field Injection
  3. Bean Scopes
  4. Lifecycle Callbacks
← Back to Spring Boot 4 Microservices & REST APIs