I use dependency injection pattern on all projects where it makes any sense, especially spring is following me all my life. Once I’ve discovered domain driven design, I’ve realized that model should be rich, clear, reusable, no meaningless dependencies.
Combining of clear model along with spring annotation can bring few issues except model dependency on spring jar files.
See following example what’s going on:
And relevant unit tests.
Once you decided to write reboust component, you can’t be absolutely sure that someone will use spring (or other DI framework) to push all dependencies.
Well, you need them check. Those are the reasons why I decided to use dependency injection via constructor. The componets just use fully supplied constructor requiring all mandatory dependencies.
See the code:
Such code brings couple of other advantages which you must not see at a glance:
- Obviously clearer code as there is just only one place where all dependencies are injected and they are final.
- Simple tests
- No more @components with tons of dependencies. This is key point. Do you remember classes which grew and grew and when you opened them last time in your favorite IDE, they had more than 15 dependecies? Well, this is not possible any more. Who would maintain constructor using 15 parameters?
- No circular dependencies. Spring allows to define bean references which leads into closed circuit. I’m surely not alone who do not like it because it’s antipattern which hide some wrong design. Once you use dependency using constructor, you will not be able to write such relation anymore.
You can browse the code in GitHub.