View RSS Feed

Spring Framework

Using Constructor Injection with Spring

Rate this Entry
by , 11-15-2011 at 02:09 PM (770 Views)
As we had mentioned in a previous tip, Inversion of Control (IoC) can be divided into two subtypes. There is Dependency Lookup which has two types, Contextualized Dependency Lookup and Dependency Pull); and Dependency Injection which also has two types, Constructor Injection and Setter Injection. In this tip we will look at Constructor Dependency Injection. Constructor Dependency Injection is Dependency Injection where a component's dependencies are provided to it in its constructor(s). The component declares a constructor or a set of constructors taking as arguments its dependencies, and the IoC container passes the dependencies to the component when it instantiates it. In this strategy, the dependent object is passed as part of the constructor call. See the following example.

Java Code:
import com.acme.springexamples.Car;
import com.acme.springexamples.dao.CarDao;

public class CarServiceImpl implements CarService {
	private CarDao carDao;

	public CarServiceImpl(CarDao carDao) {
		this.carDao = carDao;
The other aspect of constructor injection, is to change the configuration as well to align with your class. This is shown below

Java Code:
spring-config.xml with Constructor Injection
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns=""

<bean name="carDao" class="com.acme.springexamples.dao.CarDaoImpl" /></bean>
<bean name="carService" class="com.apress.springexamples.service.CarServiceImpl">
 <constructor-arg><ref bean="carDao"/></constructor-arg></bean>

Submit "Using Constructor Injection with Spring" to Facebook Submit "Using Constructor Injection with Spring" to Digg Submit "Using Constructor Injection with Spring" to Submit "Using Constructor Injection with Spring" to StumbleUpon Submit "Using Constructor Injection with Spring" to Google

Updated 11-30-2011 at 11:43 AM by Spring Framework

Dependency Injection