How to merge multiple maps into one in Spring

依然范特西╮ 提交于 2019-12-04 16:44:35

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.

Adrian Shum

I bet there is no direct support for this feature in Spring.

However, writing a factory bean to use in Spring is not that difficult (haven't tried to compile that)

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

In spring config, just do something like:

<bean id="yourResultMap" class="foo.MapMerger">
  <property name="sourceMaps">
    <util:list>
      <ref bean="carMap" />
      <ref bean="bikeMap" />
      <ref bean="motorBikeMap" />
    </util:list>
  </property>
</bean>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!