How to merge multiple maps into one in Spring

10,677

Solution 1

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>

Solution 2

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.

Share:
10,677
TimCO
Author by

TimCO

Updated on June 04, 2022

Comments

  • TimCO
    TimCO almost 2 years

    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>