2012-11-06 30 views
3

我在我的上下文文件中定義了幾個地圖。有沒有辦法將這些映射合併到一個包含所有條目的映射中,而無需編寫Java代碼(並且不使用嵌套映射)?我正在尋找相當於Map m = new HashMap(); m.putAll(carMap); m.putAll(bikeMap); 似乎應該有一種方法可以在Spring上下文文件中做到這一點,但有關util:map的Spring 3.0參考文檔部分並未涵蓋此用例。如何在春季將多個地圖合併爲一個

<!-- I want to create a map with id "vehicles" that contains all entries of the other maps --> 

<util:map id="cars"> 
    <entry key="groceryGetter" value-ref="impreza"/> 
</util:map> 

<util:map id="bicycles"> 
    <entry key="commuterBike" value-ref="schwinn"/> 
</util:map> 
+0

HTTP ://stackoverflow.com/questions/94542/can-i-compose-a-spring-configuration-file-from-smaller-ones 請檢查此解決方案,它可能會幫助 –

回答

8

在Spring中使用collection merging概念,像這樣的多個bean可以逐步合併。我在我的項目中使用了這個名稱爲merge lists,但也可以擴展爲合併地圖。

E.g.

<bean id="commonMap" 
     class="org.springframework.beans.factory.config.MapFactoryBean"> 
    <property name="sourceMap"> 
     <map> 
      <entry key="1" value="one"/> 
      <entry key="2" value="two"/> 
     </map> 
    </property> 
</bean> 
<bean id="firstMap" 
     parent="commonMap" 
     class="org.springframework.beans.factory.config.MapFactoryBean"> 
    <property name="sourceMap"> 
     <map merge="true"> 
      <entry key="3" value="three"/> 
      <entry key="4" value="four"/> 
     </map> 
    </property> 
</bean> 

第二地圖定義與第一一項所述的關聯是通過所述<bean>節點上的parent屬性來完成和在所述第一地圖中的條目與那些在第二使用<map>節點上的merge屬性合併。

+0

謝謝,但這並沒有解決我的問題,因爲車輛地圖需要有兩個父母(自行車和汽車),這是不允許的。 – TimCO

1

我敢打賭,Spring並沒有直接支持這個功能。

然而,寫一個工廠bean在Spring使用並不難(有沒有試過編譯)

public class MapMerger <K,V> implements FactoryBean { 
    private Map<K,V> result = new HashMap<K,V>(); 
    @Override 
    public Object getObject() { 
    return result; 
    } 
    @Override 
    public boolean isSingleton(){ 
    return true; 
    } 
    @Override 
    public Class getObjectType(){ 
    return Map.class; 
    } 
    public void setSourceMaps(List<Map<K,V>> maps) { 
    for (Map<K,V> m : maps) { 
     this.result.putAll(m); 
    } 
    } 
} 

在春天的配置,只是這樣做:

<bean id="yourResultMap" class="foo.MapMerger"> 
    <property name="sourceMaps"> 
    <util:list> 
     <ref bean="carMap" /> 
     <ref bean="bikeMap" /> 
     <ref bean="motorBikeMap" /> 
    </util:list> 
    </property> 
</bean> 
+0

這很好,謝謝阿德里安。在你的xml中很少有小的拼寫錯誤,應該像 TimCO