Spring Setter Injection


Spring Setter Injection

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

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 StudentBean.java 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) {
		this.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- " + this.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="http://www.springframework.org/schema/beans" 
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<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 MainClaz.java as and make a call to this xml file as given in the class


package net.roseindia;

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

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 MainClaz.java you will get the output as
Roll No- 1
Name- John Trikarson
Course- M.Tech

Download Select Source Code