Dependency Injection by setter method in Spring

The Spring IoC container also supports setter injection, which is the preferred method of dependency injection in Spring. Setter injection uses the set* methods in a class file to garner property names that are configurable in the spring XML config.

We can inject the dependency by setter method also. The <property> subelement of <bean> is used for setter injection. Here we are going to inject

  1. primitive and String-based values
  2. Dependent object (contained object)
  3. Collection values etc.

Injecting primitive and string-based values by setter method

Let's see the simple example to inject primitive and string-based values by setter method. We have created three files here:

  • applicationContext.xml

It is a simple class containing three fields id, name and city with its setters and getters and a method to display these informations.

package com.javatportal;

public class Employee {
private int id;
private String name;
private String city;

public int getId() {
	return id;
public void setId(int id) { = id;
public String getName() {
	return name;
public void setName(String name) { = name;

public String getCity() {
	return city;
public void setCity(String city) { = city;
void display(){
	System.out.println(id+" "+name+" "+city);



We are providing the information into the bean by this file. The property element invokes the setter method. The value subelement of property will assign the specified value.

<?xml version="1.0" encoding="UTF-8"?>

<bean id="obj" class="com.javatportal.Employee">
<property name="id">
<property name="name">
<property name="city">



This class gets the bean from the applicationContext.xml file and calls the display method.

package com.javatportal;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

public class Test {
	public static void main(String[] args) {
		Resource r=new ClassPathResource("applicationContext.xml");
		BeanFactory factory=new XmlBeanFactory(r);
		Employee e=(Employee)factory.getBean("obj");

Output:20 Mithilesh NewDelhi