如何在Spring中将多个地图合并成一个 [英] How to merge multiple maps into one in Spring

查看:155
本文介绍了如何在Spring中将多个地图合并成一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的上下文文件中定义了几个地图。有没有办法将这些地图组合成一个包含所有条目的地图,而不需要编写Java代码(而不使用嵌套的地图)?我正在寻找相当于Map m = new HashMap(); m.putAll(carMap); m.putAll(bikeMap);
似乎应该有一种方法在Spring上下文文件中执行此操作,但是在util:map上的Spring 3.0参考文档部分并不涵盖此用例。

 <! - 我想创建一个id为车辆的地图,其中包含其他地图的所有条目 - > 

< util:map id =cars>
< entry key =groceryGettervalue-ref =impreza/>
< / util:map>

< util:map id =bicycles>
< entry key =commuterBikevalue-ref =schwinn/>
< / util:map>


解决方案

使用集合合并概念可以逐步合并。我在我的项目中使用了这一点,以合并列表,但也可以扩展到合并地图。



例如

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

第二个地图定义与第一个地图定义的关联是通过 < bean> 节点中的父属性,第一个地图中的条目与第二个地图中的条目合并,使用< map> 节点上合并属性。


I have several maps defined in my context file. Is there a way to combine those maps into one map that contains all of their entries, without writing Java code (and without using nested maps)? I'm looking for the equivalent of Map m = new HashMap(); m.putAll(carMap); m.putAll(bikeMap); Seems like there should be a way to do this in Spring context file, but the Spring 3.0 reference doc section on util:map doesn't cover this use case.

<!-- 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>

解决方案

Using collection merging concept in Spring, multiple beans like these can be merged incrementally. I used this in my project to merge lists , but can be extended to merge maps as well.

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>

The association of the second map definition with the first one is done through the parent attribute on the <bean> node and the entries in the first map are merged with those in the second using the merge attribute on the <map> node.

这篇关于如何在Spring中将多个地图合并成一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆