Sitemap

Member-only story

đźš« Stop Using Field Injection in Spring Boot: Use Constructor Injection

4 min readApr 13, 2025

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.

⚠️ Problems with Field Injection

Field injection creates several long-term issues:

  • Dependencies are hidden — You can’t tell what this class needs just by looking at the constructor.
  • Fields are not final — You lose immutability and safety.
  • Testing becomes harder — You can’t pass mock objects directly.
  • It depends on Spring’s reflection — You cannot use it outside the Spring context.
  • Refactoring becomes risky — You might miss dependencies during changes.

âś… Use Constructor Injection Instead

Constructor injection means passing the required dependencies using a constructor. It makes your code easier to understand and maintain.

Example:

@Service
public class OrderService {

private final PaymentService paymentService;
private final NotificationService notificationService;

public…

--

--

No responses yet