Spring <idref>与<ref>的区别

Spring中,<idref>和<ref>还是比较容易混淆的。。 他们的本质区别是<idref>对应的是id的值,对应该值的property一般来说是String类型, 而<idref>对应的是bean的值, 对应该值的property是bean的类型。 这样说还是比较模糊的,看下面的例子。

package Impl;

public class Teacher {
	
	public Teacher(){
		
	}
	
	public Teacher(String name,Student student){
		
	}

}
 
package Impl;

public class Student {
	private Teacher teacher;  //Teacher类型
//	private IPhone phone;
	private String teacherId;  //String类型
	
	public Student(){
		
	}
	
	public Student(Teacher teacher){
		this.teacher = teacher;
	}

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}

	public String getTeacherId() {
		return teacherId;
	}

	public void setTeacherId(String teacherId) {
		this.teacherId = teacherId;
	}
	
}


<?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.1.xsd"
>

<bean id="student" class="Impl.Student" >
<property name="teacher">
	<ref bean="teacher"/>
</property>
<property name="teacherId">
	<idref bean="teacher"/>
</property>
</bean>



<bean id="teacher" class="Impl.Teacher">
	<constructor-arg index="0" type="java.lang.String">
		<value>Morgan</value>
	</constructor-arg>
	
	<constructor-arg index="1" ref="student">
	</constructor-arg>
</bean>

</beans>


package test;

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

import Impl.Student;

public class TestConstructorBeans {
	
	public static void main(String args[]){
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//		context.getBean("teacher");
		
		ApplicationContext context2 = new ClassPathXmlApplicationContext(new String[]{"constructorBeans.xml"},context);
		//context.getBean("phone2");
	    Student s = (Student)context2.getBean("student");
	    System.out.println(s.getTeacherId());
	}

}



需要指出的是,<idref bean="teacher"/> 可以用<value>teacher</value>替代,但是Spring是不会检出value是否存在的。。而是用idref, sping在加载的时候会检出idref的值是否存在。 因为拿到另一个bean的id, 基本上都是想在运行时通过getBean得到bean的实例。

猜你喜欢

转载自morgan117.iteye.com/blog/1844941