How to use MultiKeyMap from Apache in Spring Framework

2.4k Views Asked by At

I have come across MultiKeyMap from Apache Commons and am interested in using it in Spring framework instead of using regular map as I have a need for double key map. Dpes anyone know how to use MultiKeyMap with Spring framework?

1

There are 1 best solutions below

2
On

I didn't check, but I guess support for MultiKeyMap is not built-in Spring.

You would need to construct MultiKey instances as keys to be used with the normal Map interface methods. The most explicit way would be like this:

<map>
  <entry>
    <key><bean class="org.apache.commons.collections.keyvalue.MultiKey">
      <constructor-arg index="0"><ref bean="KEY_0_REF"/></constructor-arg>
      <constructor-arg index="1"><value>KEY_1_VALUE</value></constructor-arg>
    </bean></key>
    <value>YOUR_VALUE</value>
  </entry>
</map>

The Map produced by the <map> element is not a MultiKeyMap, so you would need to create that yourself:

<bean id="yourMultiKeyMap" class="org.apache.commons.collections.map.MultiKeyMap">
  <constructor-arg>
    <bean class="org.apache.commons.collections.map.HashedMap">
      <constructor-arg>
        <map>YOUR_MULTI-KEY_VALUE_PAIRS</map>
      </constructor-arg>
    </bean>
  </constructor-arg>
</bean>

It works (tested it with Spring 3.0.5), but it's a hell lot of XML to be written.

Using the spring-util namespace, you can reduce the map creation part to this:

<beans xmlns:util="http://www.springframework.org/schema/util"  ...>
...
<util:map id="yourMultiKeyMap" map-class="org.apache.commons.collections.map.MultiKeyMap">
  <entry>
    ...
  </entry>
</u:map>
...
</beans>

Is there a shorter way to create the MultiKey instances?

Also note that I could inject the MultiKeyMap created as a bean using the @Autowired annotation, but I could not inject a map <util:map> using the @Autowired annotation. I had to use the @Resource annotation from JSR-250.