Spring Setter Injection Example

Student.java File

package com.jtechies;

public class Student {
	private String name;
	private Course course;
	private String rollNo;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Course getCourse() {
		return course;
	}
	public void setCourse(Course course) {
		this.course = course;
	}
	public String getRollNo() {
		return rollNo;
	}
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}
	@Override
	public String toString() {
		return "name = " + name + "\n" 
			+ course + "\nrollNo = "
				+ rollNo;
	}
}

Course.java File

package com.jtechies;

public class Course {
		private String name;
		private String duration;
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getDuration() {
			return duration;
		}

		public void setDuration(String duration) {
			this.duration = duration;
		}

		public String toString(){
			return "course name = "+name+
				"\ncourse duration = "+duration;
		} 
}

Test.java File

package com.jtechies;

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

public class Test {
   public static void main(String[] args) {
     ApplicationContext context = new 
     	ClassPathXmlApplicationContext("Beans.xml");
     Student student= (Student)context.getBean("student");
     System.out.println(student);
   }
}

Beans.xml file

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    	http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans
    	/spring-beans-3.0.xsd">

   <bean id="student" class="com.jtechies.Student">
       <property name="name" value="peter"/>
       <property name="course" ref="course"/>
       <property name="rollNo" value="1001"/>
   </bean>
   <bean id="course" class="com.jtechies.Course">
       <property name="name" value="B.tech"/>
       <property name="duration" value="4 years"/>
   </bean>
</beans>

Output

name = peter
course name = B.tech
course duration = 4 years
rollNo = 1001

Ways of Accessing a Bean

There are multiple ways of accessing a bean

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

  • Classic way : In this you need to cast

    Service service = (Service) context.getBean("service");

  • Spring 3.0 : In this you no need to cast

    Service service = context.getBean("service", Service.class);

  • New in Spring 3.0 : In this you not need bean id

    Service service = context.getBean(Service.class);