If it is a forced dependency, then use the constructor injection and, if it is an optional dependency, use the Set method. Spring encourages constructor injection to ensure that a dependency is not null.
Since you can mix constructor-based and setter-based DI, it's a good rule of thumb to use constructors for mandatory Dependencies and Setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on a setter method can be used to make the property a Required dependency.
The Spring team generally advocates constructor injection as it enables one to implement application components as Immutable objects and to ensure the required dependencies is not null
. Furthermore constructor-injected components is always returned-to-client (calling) code in a fully-initialized state. As a side note, a large number of constructor arguments is a bad code smell , implying that the class likely have t OO Many responsibilities and should is refactored to better address proper separation of concerns.
Setter injection should primarily only being used for optional dependencies so can be assigned reasonable default values WI Thin the class. Otherwise, Not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is this setter methods make objects of the that class amenable to reconfiguration or re-inject Ion later. Management through JMX MBeans is therefore a compelling use case for setter injection.
Use the DI style which makes the most sense for a particular class. Sometimes, when dealing with Third-party classes for which you does not have the source, the choice are made for you. For example, if a Third-party class does not expose any setters methods, then constructor injection Le form of DI.
Spring Learning note constructor-based or setter-based DI?