Constructor vs Setter vs Field Injection

Difficulty: Beginner

Question

Spring supports constructor, setter, and field injection. Which one should you use and why is constructor injection recommended?

Answer

This is one of those questions where everybody knows the three names but only some people can defend the answer, so let's build a proper argument. Spring can inject a dependency in three places. Through a constructor, through a setter method, or directly into a field marked with @Autowired. All three work, but they are not equal in design quality, and the Spring team itself recommends constructor injection for required dependencies.

Start with field injection because it is the one you see in tutorials. You annotate a private field with @Autowired and Spring pokes the value in using reflection. It looks tidy, but it hides trouble. The class cannot be created with its dependencies outside the container without reflection tricks, so a plain unit test cannot simply call new OrderService(mockRepo). The field cannot be final, so the object is mutable. And the class can quietly accumulate ten dependencies with no visual pain, hiding a single-responsibility violation.

Constructor injection solves those problems. The dependencies are parameters, so anyone reading the class sees exactly what it needs. Fields can be final, which makes the bean immutable and thread-safe by construction. You can never get a half-initialised object, because Spring cannot create the bean until every argument is available. Unit tests are trivial. And a constructor with eight parameters is visibly ugly, which nudges you to split the class. Since Spring 4.3, a class with a single constructor does not even need @Autowired.

Setter injection has a legitimate place for optional dependencies or ones that may be reconfigured, for example an optional metrics collector that has a sensible default. The downside is that the object can be used before the setter is called, so you need to defend against nulls. It is also one way to break a circular dependency, though that is usually a symptom of poor design rather than a solution.

There is one more subtle benefit worth mentioning to interviewers: constructor injection makes circular dependencies fail immediately at startup. If A needs B in its constructor and B needs A, Spring cannot build either and reports the cycle clearly. With field or setter injection the cycle may be silently resolved through early references in older setups, hiding the design flaw. In Spring Boot 2.6 and later, circular references are prohibited by default for exactly this reason.

To summarise the rule of thumb for your answer: constructor injection for mandatory dependencies, setter injection for optional ones, and avoid field injection in production code, except perhaps in test classes or configuration where convenience wins. If you use Lombok, @RequiredArgsConstructor on a class with final fields gives you constructor injection without boilerplate, and that is very common in real teams.

Code examples

The three styles side by side

@Service
class FieldStyle {
    @Autowired
    private UserRepository repo;          // hidden, non-final, reflection only
}

@Service
class SetterStyle {
    private AuditLogger logger;
    @Autowired(required = false)
    public void setLogger(AuditLogger logger) { this.logger = logger; }
}

@Service
@RequiredArgsConstructor                  // Lombok generates the constructor
class ConstructorStyle {
    private final UserRepository repo;    // immutable, mandatory, testable
    private final EmailService emailService;
}

// Test without Spring at all
var service = new ConstructorStyle(mock(UserRepository.class), mock(EmailService.class));

The constructor style can be instantiated in a plain JUnit test with mocks, no Spring context required.

Key points

Common follow-up questions

Interview tips

Concepts covered

Constructor Injection, Field Injection, Setter Injection, Immutability

More Spring Boot questions