What is the difference between constructor injection and setter injection?

Constructor Injection and Setter Injection are two techniques used in Spring to provide dependencies to a bean. Constructor Injection supplies dependencies at the time of object creation, while Setter Injection provides them after the object has been created.

Key Points

Example

A UserService class that cannot function without a UserRepository should use Constructor Injection. A NotificationService that is optional can be injected using Setter Injection.

// Constructor Injection
@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}

// Setter Injection
@Service
public class NotificationService {

    private EmailService emailService;

    @Autowired
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }
}

Interview Tip

A concise interview answer is

Constructor Injection is used for mandatory dependencies and ensures that an object is fully initialized at creation time. Setter Injection is suitable for optional dependencies that may need to be changed later. Constructor Injection is generally recommended because it improves immutability, testability, and reliability.

Quick Comparison

Constructor Injection

Setter Injection

Last updated: 11 November 2026

Previous question: What is the best way to inject beans in Spring, and why?

Next question: What are the different bean scopes in Spring?

More Spring Framework - Level I interview questions

All Spring Framework - Level I questions