Friday, April 1, 2011

Dependency Injection

Dependency Injection i.e. Inversion Of Control. I have been asked this question so many times that "What is dependency injection?" so, I felt that I should write something about it..
So what is Dependency Injection?? Dependency Injection is the process of not to create objects explicitly but to describe how they should be created.
As I am working on Spring and Hibernate so this question has been asked for Spring, so how does spring uses it?

In Spring, it uses XML file where we describe how beans(objects) should be created, Spring uses this XML file and creates objects and we simply use these beans in our project.
Consider following scenario,

We have a class

package di.demo;
class A{
     String value;

     public void setValue(String value){
       this.value=value;
     }
}
So we describe this in Spring XML configuration file.

<bean id="aBean"
     class="di.demo.A">
 <property name="value" value="Sachin"/>
</bean>

Spring uses this configuration file, creates a new object for class A and set value for property "value". It uses Reflections for this and this is what Dependency Injection is.

No comments:

Post a Comment

Ads Inside Post