What is Dependency Injection in Spring ?

Explain DI in Spring ?

Answer : In spring objects define their associations (dependencies) and do not worry about how to get those dependencies ; now it is the responsibility of Spring to provide the required dependencies for creating objects. Spring creates the dependent objects and injects those object into the bean.

Suppose we have an object Employee and it has a dependency on object Address. So we define a bean corresponding to Employee where it will define its dependency on object Address. When Spring try to create an Object Employee it sees that Employee has a dependency on object Address so first it will create the Address object (dependent object) and then inject this into the Employee Object.

Given below is the xml configuration for injecting addressBean into the employeeBean using setter injection. To see complete example of DI click here.

		<bean id="employeeBean" class="com.thecafetechno.Employee">
		 	 <property name="name" value="Davinder"/>
		  	<property name="age" value="24"/>
		  	<property name="address" ref="addressBean"/>
		</bean>
		<bean id="addressBean" class="com.thecafetechno.Address">
		  	<property name="city" value="Hoshiarpur"/>
		  	<property name="state" value="Punjab"/>
		</bean>