Spring中的idref

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mutou_ren/article/details/89530932

idref可以用在<constructor-arg/><property/>中进入元素注入,它的作用是注入指定的bean的ID,作为字符串的形式注入,但在部署时容器会检查这个bean是否存在,从而起到错误检查的作用。
官方文档内容:

The idref element is simply an error-proof way to pass the id (a string value - not a reference) of another bean in the container to a or element. The following example shows how to use it:

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

The preceding bean definition snippet is exactly equivalent (at runtime) to the following snippet:

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

The first form is preferable to the second, because using the idref tag lets the container validate at deployment time that the referenced, named bean actually exists. In the second variation, no validation is performed on the value that is passed to the targetName property of the client bean. Typos are only discovered (with most likely fatal results) when the client bean is actually instantiated. If the client bean is a prototype bean, this typo and the resulting exception may only be discovered long after the container is deployed.

以上摘自官方文档中的两个XML内容等效,可以发现<idref bean="theTargetBean"/>最后变成了value="theTargetBean"

猜你喜欢

转载自blog.csdn.net/Mutou_ren/article/details/89530932