Spring教程-通过setter方法进行依赖注入

我们也可以通过setter方法进行依赖注入。在<bean>的<property>子元素中使用setter注入。在这里,我们将注入:
1.基本类型和字符串值
2.依赖对象(包含对象)
3.集合值等
通过setter方法注入基本类型和字符串值
让我们看一个简单的示例,通过setter方法注入基本类型和字符串值。我们创建了三个文件:
.Employee.java
.applicationContext.xml
.Test.java
Employee.java
这是一个简单的类,包含三个字段id,name和city,以及它们的setter和getter方法和一个用于显示这些信息的方法。
package cn.javatiku;
public class Employee {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
}
applicationContext.xml
通过这个文件提供信息到bean中。property元素调用setter方法。property的value子元素将指定的值分配给相应的属性。
<?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="obj" class="cn.javatiku.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Arun</value>
</property>
<property name="city">
<value>ghaziabad</value>
</property>
</bean>
</beans>
Test.java
该类从applicationContext.xml文件中获取bean,并调用display方法。
package cn.javatiku;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e=(Employee)factory.getBean("obj");
s.display();
}
}
输出结果:20 Arun ghaziabad