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?
-
What do you mean, "use with"? – skaffman May 03 '11 at 20:55
1 Answers
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.

- 8,913
- 2
- 32
- 39
-
Thank you for the suggestion. In the
tag, how could we define two keys? Could you help? – JUG May 05 '11 at 19:11 -
I don't know of a shorter way than explicitly constructing a bean of class `MultiKey` as the key, as shown in the first code fragment of the answer. – Christian Semrau May 05 '11 at 20:01