View RSS Feed

Spring Framework

Using Constructor Injection with Spring

Rate this Entry
by , 11-15-2011 at 03:09 PM (871 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="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 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>
</beans>

Submit "Using Constructor Injection with Spring" to Facebook Submit "Using Constructor Injection with Spring" to Digg Submit "Using Constructor Injection with Spring" to del.icio.us Submit "Using Constructor Injection with Spring" to StumbleUpon Submit "Using Constructor Injection with Spring" to Google

Updated 11-30-2011 at 12:43 PM by Spring Framework

Categories
Dependency Injection

Comments