Seagull
Seagull

Reputation: 2299

How to define an EnumMap in Spring 3.0

I've been trying to define an EnumMap in Spring using . I tried the following variations

<util:map map-class="java.util.EnumMap" key-type="xyz.EnumType">
<entry key="SOME_ENUM_TYPE">
   <ref bean="someBean"/>
</entry>
</util:map>

I get the following error

Error creating bean with name 'util:map#1c599b0e': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.util.EnumMap]: No default constructor found; nested exception is java.lang.NoSuchMethodException: java.util.EnumMap.<init>()

The following definition is what I tried initially

<util:map map-class="java.util.EnumMap">
<entry key="SOME_ENUM_TYPE">
   <ref bean="someBean"/>
</entry>
</util:map>

and this gave me some error of not being able to assign the enumtype to String.

There are examples on the site to using a generic map, but I am trying to see whether I can use an EnumMap, since it's considered the most optimal for Enums. The answer might be very obvious, so my apologies if the question is stupid. This is probably due to my limited knowledge of Spring. Thanks

Upvotes: 9

Views: 4312

Answers (2)

zg_spring
zg_spring

Reputation: 359

This problem is because the EnumMap hasn't the default constructor with no argument. Spring will be init by no argument, if no exist will be error.

Upvotes: 0

axtavt
axtavt

Reputation: 242686

I guess you cannot initialize EnumMap with <util:map>. However, EnumMap has a constructor that takes an existing Map, you can try to use it:

<bean class = "java.util.EnumMap">
    <constructor-arg>
        <util:map key-type="xyz.EnumType">
            <entry key="SOME_ENUM_TYPE"><ref bean="someBean"/></entry>
        </util:map> 
    </constructor-arg>
</bean>

Upvotes: 14

Related Questions