2012-02-16 87 views
0

我有一些我創建的bean,它們都使用類似的模式進行bean實例化。頂層對象都非常相似,但它們包含的對象因字符串構造函數參數而異。除了兩個THIS CHANGES A實例和一個THIS CHANGES B實例外,每個頂級bean中的所有內容都是相同的。下面是我的一個豆子。除了THIS CHANGES值之外,其他值完全相同。如何在Spring應用程序上下文中減少重複

<bean id="mover1" class="CustomDataMover"> 
     <constructor-arg ref="session"/> 
     <constructor-arg> 
      <bean class="DataCache"> 
       <constructor-arg> 
        <bean class="AllValuesReader"> 
         <constructor-arg ref="databaseConnector"/> 
         <constructor-arg value="THIS CHANGES A"/> 
         <constructor-arg value="v1"/> 
         <constructor-arg value="v2"/> 
        </bean> 
       </constructor-arg> 
      </bean> 
     </constructor-arg> 
     <constructor-arg ref="customUpdate"/> 
     <constructor-arg value="THIS CHANGES B"/> 
     <constructor-arg> 
      <bean class="ValueGenerator"> 
       <constructor-arg> 
        <bean class="LatestValueRetriever"> 
         <constructor-arg ref="databaseConnector"/> 
         <constructor-arg value="v3"/> 
         <constructor-arg value="v4"/> 
         <constructor-arg value="THIS CHANGES A"/> 
        </bean> 
       </constructor-arg> 
      </bean> 
     </constructor-arg> 
</bean> 

如何減少我的豆中的重複量?我正在尋找某種方式來製作某種模板。另外,請注意我有其他豆的參考。

回答

5

您可以使用抽象bean定義作爲模板來減少重複。例如:

<bean id="parent" abstract="true"> 
    <constructor-arg value="ARG0"/> 

    <property name="propertyA" value="A"/> 
    <property name="propertyB" value="B"/> 
    <property name="propertyC" ref="beanC"/> 
</bean> 

<bean id="child1" class="SomeClass" parent="parent"> 
    <property name="propertyD" value="D1"/> 
</bean> 

<bean id="child2" class="SomeOtherClass" parent="parent"> 
    <property name="propertyD" value="D2"/> 
</bean> 

豆「child1」和「的child2」將從「父」共同價值觀爲arg0中,「propertyA」,「propertyB」和「propertyC」,而且還能夠配置自己的價值觀爲「propertyD」。

請注意,「父」沒有類,因此無法實例化。還要注意,「child1」和「child2」可以是完全不同類的同一個抽象bean定義的子元素 - 這個層次結構與類層次結構無關。

+0

如何將這個應用到嵌套類?我可以使頂層實例抽象,然後將值傳遞給嵌套元素? – 2012-02-16 17:04:31

相關問題