2012-06-13 163 views
1

我對Spring相當陌生,我需要一個有兩個屬性的bean--第二個是引用第一個屬性的內聯bean。類似這樣的:配置Spring Bean重新使用它自己的屬性?

<bean id="aBean" class="com.sample.Bean"> 
    <property name="propertyOne" value="something" /> 
    <property name="propertyTwo"> 
     <bean class="com.sample.AnotherBean"> 
      <property name="propertyThree" ref="propertyOne /> 
     </bean> 
    </property> 
</bean> 

製作propertyOne它自己的bean不是這裏的選項。什麼是實現這一目標的最佳方式?謝謝!

回答

1

我能想到的唯一方法就是爲您的公共財產創建一個bean,並在BeanAnotherBean中引用此公共屬性 - 爲什麼這不是您的選擇?

任何其他方式都不行,因爲依賴關係圖-aBean依賴於另一個Bean,因此AnotherBean將在aBean之前實例化,並且將無法引用子bean屬性。

如果不曾有過這種依賴關係,你也可以使用Spring的EL指屬性:

<property name="propertyThree" value="${aBean.propertyOne}"/> 
+0

這是我如何解決該問題得到。我希望Spring提供了一個更優雅的解決方案,但是,如果我正在開發的應用程序的性能比Spring好一半,那麼我首先不會遇到這個問題。 – Michael

1

您可以創建「propertyOne」作爲一個單獨的bean。

並引用來自aBean和你的內聯bean。

<bean id="propertyOne" class="java.lang.String"> 
    <constructor-arg><value>"blabla"</value></constructor-arg> 
</bean> 

<bean id="aBean" class="com.test.SimpleBean"> 
<property name="name" ref="firstProperty" /> 
<property name="newBean"> 
    <bean class="com.test.OtherSimplwBean"> 
     <property name="otherName" ref="propertyOne" /> 
    </bean> 
</property> 

+1

感謝您的回覆。不幸的是,這在我的應用中不會成爲一種選擇,正如我的問題所述。 – Michael