Spring > Setter Injection

Spring Setter Injection

In this example you will learn how to set a bean property via setter injection. Consider the following User bean class.

package com.w3javaguide;

public class User {

    private String name;
    private int age;
    private String country;
    public String getName() {
    	return name;
    public void setName(String name) { = name;
    public int getAge() {
    	return age;
    public void setAge(int age) {
    	this.age = age;
    public String getCountry() {
    	return country;
    public void setCountry(String country) { = country;
    public String toString() {
    	return name + " is " + age + " years old, living in " + country;

The User bean class has three attributes viz. name, age and country. All the three attributes are set using the setter injection. The toString() method of the User bean class is overridden to display the user object.

Here the beans.xml file is used to do spring bean configuration. The following code shows how to set a property value thru setter injection.

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

    <bean id="user" class="com.w3javaguide.User" >
        <property name="name" value="arandev" />
        <property name="age" value="24"/>
        <property name="country" value="India"/>


The id attribute of the bean element is used to specify the bean name and the class attribute is used to specify the fully qualified class name of the bean. The property element with in the bean element is used to inject property value via setter injection. The name attribute of the property element represents the bean attribute and the value attribute specifies the corresponding property value.

Here we set "arandev", "24" and "India" for the User bean properties name, age and country respectively. The following Main class is used to get the User bean from the Spring IoC container and dispaly its value it to the user.

package com.w3javaguide;

import org.springframework.context.ApplicationContext;
import ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User)context.getBean("user");


On executing the Main class the following message gets displayed on the console.

arandev is 24 years old, living in India

You can download and try the Spring setter injection example by clicking the Download link below.

Source :Download
Source + Lib :Download
Contact Us  |  Copyright © 2012