---
title: "Spring <idref>与<ref>的区别"
author: "morgan117"
date: "2013-04-10T11:13:36Z"
tags: ["Bean", "Spring"]
categories: ["企业架构"]
slug: "spring-idref-ref"
draft: false
lastmod: "2013-04-10T11:13:36Z"
id: 1844941
url: "https://morgan117.iteye.com/blog/1844941"
---

Spring中,和还是比较容易混淆的。。 他们的本质区别是对应的是id的值，对应该值的property一般来说是String类型， 而对应的是bean的值， 对应该值的property是bean的类型。 这样说还是比较模糊的，看下面的例子。 \[code="java"] package Impl; public class Teacher { public Teacher(){ } public Teacher(String name,Student student){ } } \[/code] \[code="java"] 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; } } \[/code] \[code="java"] Morgan \[/code] \[code="java"] 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()); } } \[/code] 需要指出的是， 可以用teacher替代，但是Spring是不会检出value是否存在的。。而是用idref， sping在加载的时候会检出idref的值是否存在。 因为拿到另一个bean的id， 基本上都是想在运行时通过getBean得到bean的实例。