idref
元素用来将容器内其它bean的id传给<constructor-arg/>
或 <property/>
元素,同时提供错误验证功能。prototype
<bean id="theTargetBean" class="..."/> <bean id="theClientBean" class="..."> <property name="targetName"> <idref bean="theTargetBean" /> </property> </bean>
上述bean定义片断彻底地等同于(在运行时)如下的片断:code
<bean id="theTargetBean" class="..." /> <bean id="client" class="..."> <property name="targetName" value="theTargetBean" /> </bean>
第一种形式比第二种更可取的主要缘由是,使用idref
标记容许容器在部署时 验证所被引用的bean是否存在。而第二种方式中,传给client
bean的targetName
属性值并无被验证。任何的输入错误仅在client
bean实际实例化时才会被发现(可能伴随着致命的错误)。若是client
bean 是prototype类型的bean,则此输入错误(及由此致使的异常)可能在容器部署好久之后才会被发现。xml
此外,若是被引用的bean在同一XML文件内,且bean名字就是bean id,那么能够使用local
属性,此属性容许XML解析器在解析XML文件时对引用的bean进行验证。部署
<property name="targetName"> <!-- a bean with an id of 'theTargetBean' must exist; otherwise an XML exception will be thrown --> <idref local="theTargetBean"/> </property>