I am currently re-reading "Effective Java" while working at a shop that makes heavy use of Spring Dependency Injection. When reading Bloch's book one cannot help but pick up on the emphasis he places on immutability in classes(he states several times that classes should be as immutable as possible). I can't help but feel this in direct conflict with the reliance that Spring Dependency Injection( and most DI engines for that fact) has on the javabeans standard. Reading 'Spring in Action' the chapters on DI seem like they would make Bloch cringe with their mutable classes composed of objects instantiated outside of your purview that could be mutable in their own right.
Is it that Bloch's ideas are too novel for Spring? Is the Spring model busted? Does Bloch's stance on immutability only apply to writing library code? When writing Spring code should I write flexible objects with lots of getters and setters or load everything up in the constructor?
In fact, spring beans are immutable by idea, even though you are not enforcing this.
You can provide only a getter to a final
field that is initialized through constructor injection.
Usually you don't do so, but you are never supposed to reassign fields of beans that are injected by the DI framework. That's because spring beans usually do not hold any state, apart from their dependencies (and their scope is singleton). Of course, there are exceptions, like prototype and request scoped beans, that these are rare (for example in 2 big and 2 medium projects I've used only 1 prototype-scoped bean)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With