spring的一個細節

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>
相關文章
相關標籤/搜索