Share on Google+Share on Google+

Spring Setter Injection

In this tutorial you will learn that how to inject the instance variable value in Spring framework

Spring Setter Injection

The In Spring framework Setter Injection is used to inject the value into the instance variable from the xml file without hard coding into the java fil. For this we create a XML file. In this file we map the bean class and there attributes and specify the default value into it. Some steps are given below to inject the value into the bean property.

At First create the Bean class as

package net.roseindia;

public class StudentBean {
	private int roll;
	private String name;
	private String course;

	public int getRoll() {
		return roll;

	public void setRoll(int roll) {
		this.roll = roll;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getCourse() {
		return course;

	public void setCourse(String course) {
		this.course = course;

	public String toString() {
		System.out.println("Roll No- " + this.roll);
		System.out.println("Name- " +;
		System.out.println("Course- " + this.course);
		return super.toString();


Then make the configuration of this bean file into the xml file say StudentBean.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" 
<bean id="student" class="net.roseindia.StudentBean">
<property name="roll" value="1" />
<property name="name" value="John Trikarson" />
<property name="course" value="M.Tech" />

After this call the use this Bean into your application as
Write a main class say as and make a call to this xml file as given in the class

package net.roseindia;

import org.springframework.context.ApplicationContext;

public class MainClaz {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
		StudentBean bean = (StudentBean) context.getBean("student");

As in the above StudentBean.xml file the value to the bean instance variable is Injected so when you will run this you will get the output as
Roll No- 1
Name- John Trikarson
Course- M.Tech

Download Select Source Code



Posted on: October 20, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null