2

我的上下文文件中定义了几个地图。有没有一种方法可以将这些映射组合成一个包含所有条目的映射,而无需编写 Java 代码(并且不使用嵌套映射)?我正在寻找相当于 Map m = new HashMap(); m.putAll(汽车地图); 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>
4

2 回答 2

7

使用Spring 中的集合合并概念,像这样的多个 bean 可以增量合并。我在我的项目中使用它来合并列表,但也可以扩展到合并地图。

例如

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

第二个映射定义与第一个映射定义的关联是通过节点parent上的属性完成的,并且使用节点上的属性<bean>将第一个映射中的条目与第二个映射中的条目合并。merge<map>

于 2012-11-06T02:13:31.090 回答
1

我敢打赌,Spring 中没有直接支持此功能。

但是,编写一个在 Spring 中使用的工厂 bean 并不难(还没有尝试编译)

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);
    }
  }
}

在 spring 配置中,只需执行以下操作:

<bean id="yourResultMap" class="foo.MapMerger">
  <property name="sourceMaps">
    <util:list>
      <ref bean="carMap" />
      <ref bean="bikeMap" />
      <ref bean="motorBikeMap" />
    </util:list>
  </property>
</bean>
于 2012-11-06T03:13:28.163 回答