Pages

Sunday, July 29, 2012

spring what is dependency injection?

Dependency injection is a main feature of spring framework. This basically enables the injection of dependencies to a bean.

The example below explains this concept.

Say for an example there is a college class. Then this entity has a list of students, books, lecturers etc... Now we know that the students, books, lecturers are dependencies of college. That is the college class will have to use instances of the above mentioned dependencies. So we can inject these dependencies through an xml configuration file. Now if we call for the college bean through the ApplicationContext class for a bean of college, it will automatically pass the other dependencies as well (a list of student, books and lecturers.). The bean will have initial configured status with the dependencies. Therefore eliminating the requirement of making a list of dependencies by using new keyword for each of the dependency objects.

By default the beans follows the singleton pattern unless you specify the scope to something else. If you specify the scope to prototype, then spring will create object when a new bean is requested from  spring. Other than singleton and prototype, there are 3 other scopes and they are basically for web based applications.

No comments:

Post a Comment