View RSS Feed

Spring Framework

Using Setter Injection in Spring

Rate this Entry
by , 11-15-2011 at 02:02 PM (955 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) {
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:
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns=""

<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>

Submit "Using Setter Injection in Spring" to Facebook Submit "Using Setter Injection in Spring" to Digg Submit "Using Setter Injection in Spring" to 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)

Dependency Injection , Bean , Configuration