Spring <idref>与<ref>的区别

本文详细解释了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的实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值