Difference between constructor and setter injection in Spring or Spring Boot
1 min readJan 22, 2020
Difference between constructor and setter injection
There are many key differences between constructor injection and setter injection.
- Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by setter method only.
- Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection.
- Changes: We can easily change the value by setter injection. It doesn’t create a new bean instance always like constructor. So setter injection is flexible than constructor injection.
When use Setter Injection and constructor
Setter injection to inject dependency on any been managed by Spring’s IOC container.
On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.