---
title: "idref元素"
author: "chenchh"
date: "2010-05-26T16:54:02Z"
tags: []
categories: ["企业架构"]
slug: "idref"
draft: false
lastmod: "2010-05-26T16:54:02Z"
id: 676106
url: "https://chenchh.iteye.com/blog/676106"
---

idref元素用来将容器内其他bean的id传给&lt;constructor-arg/&gt;或&lt;property/&gt;元素，同时提供错误验证功能。

```
<bean id="theTargetBean" class="...">
    <bean id="theClientBean" class="...">
        <property name="targetName">
              <idref bean="theTargetBean"/>
        </property>
    </bean>
</bean>
```

    上述bean定义片段完全等同于（在运行时）以下的代码片段：

```
<bean id="theTargetBean" class="...">
    <bean id="theClientBean" class="...">
        <property name="targetName">
              <value>theTargetBean</value>
        </property>
    </bean>
</bean>
```

    第一种形式比第二种形式更可取的主要原因是，使用idref标记允许容器在部署时验证所被引用的bean是否存在。而第二种方式中，传给client bean的targetName属性值并没有被验证。任何的输入错误仅在client bean实际实例化时才会被发现（可能伴随致命的错误）。如果client bean是prototype类型的bean，则此输入错误（及由此导致的异常）可能在容器部署很久以后才会被发现。

    此外，如果被应用的bean在同一xml文件内，且bean名字就是id，那么可以使用local属性，此属性允许xml解析器在解析xml文件时来对引用的bean进行验证。

```
<property name="targetName">
    <idref local="theTargetBean"/>
</property>
```