Skip to main content

Spring Dependency Injection

Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods.

***Setter Dependency Injection (SDI): ***

This is the simpler of the two DI methods. In this, the DI will be injected with the help of setter and/or getter methods. Now to set the DI as SDI in the bean, it is done through the bean-configuration file For this, the property to be set with the SDI is declared under the property tag in the bean-config file.

package com.rmavuluri.org;

import com.rmavuluri.org.IEmployee;

public class EmployeeBean {

// The object of the interface IEmployee
IEmployee employee;

// Setter method for property employee
public void setEmployee(IEmployee employee){
this.employee = employee;
}
}

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="EmployeeBean" class="com.rmavuluri.org.IEmployee">
<property name="employee">
<ref bean="TESTEMPLOY" />
</property>
</bean>
<bean id="TESTEMPLOY" class="com.rmavuluri.org.impl.TESTEMPLOY" />
</beans>

***Constructor Dependency Injection (CDI): ***

In this, the DI will be injected with the help of constructors. Now to set the DI as CDI in bean, it is done through the bean-configuration file For this, the property to be set with the CDI is declared under the constructor-arg tag in the bean-config file.

package com.rmavuluri.org;

import com.rmavuluri.org.IEmployee;

public class EmployeeBean {

// The object of the interface IEmployee
IEmployee employee;

// Setter method for property employee
public void setEmployee(IEmployee employee){
this.employee = employee;
}
}
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="GFG" class="com.rmavuluri.org.EmployeeBean">
<constructor-arg>
<bean class="com.rmavuluri.org.impl.TESTEMPLOY" />
</constructor-arg>
</bean>

<bean id="Testemployee" class="com.rmavuluri.org.impl.TESTEMPLOY" />
</beans>