0

我一直在用Spring進行實驗。我希望通過使用SpEL複製另一個bean的bean的值和引用屬性。使用SpEL複製一個bean的引用不起作用

考慮這個bean:

<bean id="kenny" class="com.springinaction.springidol.Instrumentalist"> 
    <property name="song" value="#{'Jingle Bells'}" /> 
    <property name="instrument" ref="piano" /> 
</bean> 

我想它的值複製到另一個bean中,如下圖所示:

<bean id="carl" class="com.springinaction.springidol.Instrumentalist"> 
    <property name="song" value="#{kenny.song}" /> 
    <property name="instrument" ref="#{kenny.instrument}" /> <-- I GET EXCEPTION OVER HERE 

</bean> 

不過,我得到了第二prpoperty一個例外,因爲它不設法複製肯尼的手段。這首歌是正確複製沒有任何異常被拋出

我得到這個異常:在線程

異常「主」 org.springframework.beans.factory.BeanCreationException:錯誤 創建名稱爲豆「卡爾'在類路徑資源中定義 [Beans.xml]:設置bean屬性'instrument'時無法解析對bean'#{kenny.instrument}' 的引用;嵌套的異常是 org.springframework.beans.factory.BeanExpressionException:表達式 解析失敗;嵌套的異常是 org.springframework.expression.spel.SpelEvaluationException: EL1008E:(POS 6):字段或屬性 '儀器' 不能對類型的 對象中找到 'com.springinaction.springidol.Instrumentalist'

任何想法如何我可以複製儀器並將其設置爲ID爲「carl」的bean?

回答

3

A ref是對另一個bean的引用;在你的情況下,你想使用kenny bean的instrumemt屬性的值。

您應該使用

<property name="instrument" value="#{kenny.instrument}" /> 

這是假設有上Instrumentalist一個getInstrument()方法。

+0

感謝它的工作。爲什麼我添加引用的唯一原因是因爲kenny所指的工具也是一個bean。 – Goaler444

+1

肯尼特產的來源是一個豆,這並不重要;在解決這個問題時,這種關聯會丟失 - 您可以使用'ref =「piano」'或'value =「#{kenny.instrument}'。 –