View RSS Feed

Spring Framework

Using Setter Injection in Spring

Rate this Entry
by , 11-15-2011 at 02:02 PM (953 Views)
An object is created in the Spring IOC container by invoking the zero-argument constructor. In this Setter Dependency Injection, the IoC container injects a component's dependencies into the component via JavaBean-style setter methods. A component's setters expose the set of the dependencies the IoC container can manage The dependent object is then passed as a parameter to the setter method. The CarService object needs data access objects (DAO) to execute data- base operations. The data access objects are injected via setter methods, as shown in Listing below:

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

public class CarServiceImpl implements CarService {
	private CarDao carDao;

	public CarServiceImpl() {
	}

	public CarDao getCarDao() {
		return carDao;
	}

	public void setCarDao(CarDao carDao) {
		this.carDao = carDao;
	}

	public void prepareCar(Car car) {
		carDao.prepareCar(car);
	}
}
This time rather than passing in the CarDao object via the constructor for Car ServiceImpl, it is instead passed by the Spring IOC container using the setCarDao method. There is some work to do in terms of configuration that you must do in order that Spring can resolve the relevant objects and do dependency injection. This is shown in the Spring configuration file below.

Java Code:
springexamples.xml:
<?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.CatDaoImpl" /> </bean>
<bean name="carService" class="com.acme.springexamples.service.CatServiceImpl">
<property name="carDao" ref="carDao" /> </bean>
</beans>

Submit "Using Setter Injection in Spring" to Facebook Submit "Using Setter Injection in Spring" to Digg Submit "Using Setter Injection in Spring" to del.icio.us Submit "Using Setter Injection in Spring" to StumbleUpon Submit "Using Setter Injection in Spring" to Google

Updated 11-15-2011 at 02:10 PM by Spring Framework (Error in constructor for class)

Categories
Dependency Injection , Bean , Configuration

Comments