Reputation: 805
I am reading Spring documentation and I am wondering what they meant by writing:
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.
I don't see in what way does it enable to implement components as immutable. Though I understand that using constructor-based DI is similar to a natural, Java way of creating objects of a class with final fields thus preventing object from changing fields references.
Was it the only reason they used such a phrase? Could someone explain that to me?
Thank you.
Upvotes: 4
Views: 1939
Reputation: 8841
If you have a class with dependencies and all of those dependencies are provided as constructor arguments, then you can know that the object will never exist in a state where dependencies are invalid (unless you explicitly passed nulls or wrong values, but you could do some validation in the constructor if you wanted).
Your class no longer needs setters for those dependencies, therefore you know that it is not possible (assuming the fields are private) for rogue code in your application to replace valid dependencies with invalid ones . This might especially apply if the bean has high visibility (e.g., application scope) and was used by many client objects.
It would be possible that the class could be made completely immutable (there is no way to change its state after it has been created). This would be the case if there were no setters or any other methods that modified the state, and all of the fields were private.
An immutable object is much more likely to be well behaved in an multithreaded application. Although the class still needs to be made internally thread-safe, you don't have to worry about external clients coordinating access to the object.
Upvotes: 7