Constructor versus setter injection

As we can see, Spring supports three types of DI methods; however, field-based dependency is not recommended by Spring. So, constructor-based and setter-based DI are standard ways to injecting beans in your application. The selection of constructor or setter methods depends on your application requirements. In this table, we will see the different use cases of constructor and setter injection, and some best practices that will help us decide when to use setter injection over constructor injection, and vice versa:

Constructor injection

Setter injection

Best choice when the dependency is mandatory.

The suitable choice when the dependency is not mandatory.

Constructor injection makes the bean class object immutable.

Setter injection makes the bean class object mutable.

Constructor injection cannot override setter injected values.

Setter injection overrides the constructor injection when we use both constructor and setter injection for the same property.

Partial dependencies are not possible with constructor injection because we must pass all the arguments in the constructor, otherwise, it gives an error.

Partial dependency is possible with setter injection. Suppose we have three dependencies, such as int, string, and long, then with the help of a setter injection, we can inject only the required dependency; other dependencies will be taken as a default value of those primitives.

Creates a circular dependency between objects.

Resolves circular dependency issue in your application. In case of circular dependency, it is better to use a setter instead of constructor injection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset