Member-only story
đźš« Stop Using Field Injection in Spring Boot: Use Constructor Injection
If you’re using @Autowired
on private fields in your Spring Boot application, it's time to consider a better approach. While field injection looks simple, it causes problems in the long run — especially when you need to test, maintain, or extend your code.
Constructor injection is the preferred way to inject dependencies in Spring. It’s clean, safe, and easy to work with.
This article explains why field injection is not recommended, how constructor injection solves those issues, and how you can refactor your code step by step.
❌ What Is Field Injection?
Field injection uses the @Autowired
annotation on class fields like this:
@Service
public class OrderService {
@Autowired
private PaymentService paymentService;
@Autowired
private NotificationService notificationService;
// business logic...
}
It works, but it hides the actual dependencies. You cannot see what this class depends on unless you read the whole code.