Spring Setter Injection

Spring Framework allows to inject the dependency by setter method also. The <property> subelement of <bean> is used for setter injection.

There are following values injected through setter injection.

  • Primitive Values
  • Dependent Object
  • Collection values

Here I am taking example to inject Primitive values using Setter injection.

Employee.java

package com.startwithjava;
public class Employee {
private String name;
private String city;
private String state;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void display(){
System.out.println("Name:"+name+"\tCity:"+city);
}
}

applicationContext.xml

This file contains the <bean> entry for Employee class.

<?xml version="1.0" encoding="UTF-8"?> 
 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
 <bean id="emp" class="com.startwithjava.Employee">
 <property name="name" value="Raj" />
  <property name="city" value="New Delhi" />
   <property name="state" value="New Delhi" />
   <property name="salary" value="5000" />
 </bean> 
 </beans> 

Test.java

This file contains the code to obtain emp bean from applicationContext.xml.

package com.startwithjava;
import java.util.List;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test { 
public static void main(String[] args) { 
    Resource r=new ClassPathResource("applicationContext.xml"); 
    BeanFactory factory=new XmlBeanFactory(r); 
    Employee e1 = (Employee) factory.getBean("emp");
    e1.display();
} 
} 

Leave a Reply