ref作为属性
<bean id="students" class="com.yiwen.Students">
<property name="group" ref="group">
</bean>
<bean id="group" class="com.yiwen.Group" />
ref作为标签
local=”group” 表示在该xml文件中查找group(Spring4.0 没有local属性了,它的作用其实和ref属性一样,用属性也行)
<bean id="students" class="com.yiwen.Students">
<property name="group" >
<ref local="group">
</property>
</bean>
<bean id="group" class="com.yiwen.Group">
bean=”group” 表示全局查找id为group的bean,可在不同的xml中查找group
spring-main.xml
```
<bean id="students" class="com.yiwen.Students">
<property name="group" >
<ref bean="group">
</property>
</bean>
```
spring-part.xml
<bean id="group" class="com.yiwen.Group">
1
这样spring-main.xml中一样可以找到spring-part.xml中的id为group的bean
使用ref标签的实例
虽然直接使用ref属性非常简单方便,但是有时候xml文件存在多个,利用bean,不管在不在一个xml文件中都可以识别到。
编写三个类School 和Students Teachers
Teachers
public class Teachers {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Students
public class Students {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
School
public class School {
private Students students;
private Teachers teachers;
public School(Students students, Teachers teachers) {
this.students = students;
this.teachers = teachers;
}
public Students getStudents() {
return students;
}
public Teachers getTeachers() {
return teachers;
}
}
配置xml文件
<?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.xsd">
<bean id="school" class="com.yiwen.test6.School">
<constructor-arg name="students">
<ref bean="students"></ref>
</constructor-arg>
<constructor-arg name="teachers">
<ref bean="teachers"></ref>
</constructor-arg>
</bean>
<bean id="students" class="com.yiwen.test6.Students" >
<property name="name">
<value type="java.lang.String">yiwen</value>
</property>
</bean>
<bean id="teachers" class="com.yiwen.test6.Teachers">
<property name="name">
<value type="java.lang.String">zhangsan</value>
</property>
</bean>
</beans>
测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("test6.xml");
School school=(School)context.getBean("school");
System.out.print("student name:"+school.getStudents().getName()+"teacher name :"+school.getTeachers().getName());
}
}
结果如下所示:
student name:yiwenteacher name :zhangsan
1
2
表明Students和Teacher的bean已经装配到了School中了。