Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutability and Spring

Tags:

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?

like image 414
nsfyn55 Avatar asked Apr 20 '11 14:04

nsfyn55


1 Answers

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)

like image 105
Bozho Avatar answered Nov 15 '22 09:11

Bozho