Reputation: 424
As per definiton of Spring bean , POJO should have a no -arg constructor. Considering the benefits of Constructor based DI wherein by looking at the constructor itself we come to know what are its dependencies,doesnt having a no arg constructor removes this advantage.
Upvotes: 0
Views: 719
Reputation: 7630
Constructor based dependency injection is more predictive and creates immutable , fully initialised objects. Setter based DI is for dependencies considered optional, but also allows further reconfiguration of the object at a later stage. Both are valid, both have trade-offs, and therefore both are widely used.
From Spring documentation (see Constructor-based or setter-based DI? box):
The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null. Furthermore constructor-injected components are 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 has too many responsibilities and should be refactored to better address proper separation of concerns.
Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later.
(highlights are mine)
Upvotes: 3