Setter Injection in Spring: What It Is and How It Works
@Autowired or XML configuration to inject required components through public setter methods, allowing flexible and optional dependency setup.How It Works
Setter injection works by letting Spring create an object first, then calling its setter methods to provide the needed dependencies. Imagine you buy a toy car that comes without batteries, and later you add batteries yourself. Similarly, Spring creates the object and then "adds" the dependencies by calling setters.
This approach allows you to change or add dependencies after the object exists, making it flexible. It also means dependencies can be optional, as you can choose not to call some setters if they are not needed.
Example
This example shows a simple Spring component where a MessageService is injected into a Notification class using setter injection.
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component class MessageService { public String getMessage() { return "Hello from MessageService!"; } } @Component class Notification { private MessageService messageService; @Autowired public void setMessageService(MessageService messageService) { this.messageService = messageService; } public void notifyUser() { System.out.println(messageService.getMessage()); } } // In a Spring Boot application, Notification bean can be used like this: // @SpringBootApplication // public class App { // public static void main(String[] args) { // ApplicationContext context = SpringApplication.run(App.class, args); // Notification notification = context.getBean(Notification.class); // notification.notifyUser(); // } // }
When to Use
Setter injection is useful when dependencies are optional or can change after object creation. For example, if a service can work with or without a certain helper component, setter injection lets you provide that helper only when needed.
It is also helpful in testing, where you might want to replace dependencies with mocks by calling setters. However, if a dependency is mandatory, constructor injection is usually better to ensure the object is always fully ready.
Key Points
- Setter injection uses public setter methods to provide dependencies after object creation.
- It allows optional and changeable dependencies.
- Spring supports setter injection via
@Autowiredon setters or XML configuration. - It is less strict than constructor injection but can lead to partially initialized objects if not used carefully.