Dependency Injection With Spring by Example
I think every developer these days have heard this term “Dependency Injection” or “Inversion of Control” before Martin Fowler coined the term “Dependency Injection”. And how many people are confused by that? Or may be I’m the only one who does not know what it means by injecting something into something and every developer should be happy about it.
I really recommend you to read this article first by Martin Folwer, he has explained it in a very simple way and easy to understand. Additionally, I cannot think of any simpler example to explain than of Martin’s article. So, please do read Martin’s article and Spring in Action for more information.
So, in my example and this is purely from my understanding.
A class student that needs to go to school. You can see that student class is tightly coupled with the class FindARouteToSchool. You can’t have Student without FindARouteToSchool. This is not so bad, but many developers find it not flexible enough. We need to promote loosely coupled.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
So, we need something that can inject something into the Student class, so the class is not dependent to FindARouteToSchool. I have chosen Spring to solve the problem and create a setter object to set a reference of the class FindARouteToSchool.
This is the new Student class which has one more method to set FindARouteToSchool reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
This is the XML configure file of Spring
1 2 3 4 5 6 7 8 9 10 11 12 13