Hi Martin,

Originally Posted by
sylvestris
I want to use enums as keys in a map within the context.xml. The following doesn't work. Any ideas on what I should do?
Yes. First and foremost, "com.abc.Colour.RED" is not a class. So that configuration could never work.
You need to access the RED enum constant as a static field. This can be achieved with the util namespace as follows:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<util:constant id="red" static-field="com.abc.Colour.RED" />
<bean id="redMapper" class="com.abc.RedMapper" />
<bean id="mybean" class="com.abc.MyBean">
<property name="mappers">
<map>
<entry key-ref="red" value-ref="redMapper" />
</map>
</property>
</bean>
</beans>
To prove that it works, I threw together a mini unit test using the following classes:
Code:
package com.abc;
public enum Colour {
RED, GREEN, BLUE;
}
Code:
package com.abc;
public interface ColourMapper {}
Code:
package com.abc;
public class RedMapper implements ColourMapper {}
Code:
package com.abc;
import java.util.HashMap;
import java.util.Map;
public class MyBean {
private final Map<Colour, ColourMapper> mappers = new HashMap<Colour, ColourMapper>();
public Map<Colour, ColourMapper> getMappers() {
return this.mappers;
}
public void setMappers(Map<Colour, ColourMapper> mappers) {
this.mappers.putAll(mappers);
}
}
Code:
package com.abc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EnumColourMapperTests {
@Autowired
private MyBean myBean;
@Test
public void colourMappingConfig() {
assertNotNull(myBean);
assertEquals(1, myBean.getMappers().size());
assertTrue(myBean.getMappers().containsKey(Colour.RED));
assertEquals(RedMapper.class.getName(), myBean.getMappers().get(Colour.RED).getClass().getName());
}
}
If you want to try out this code, simply store the XML application context configuration listed at the top of this post in your classpath as com/abc/EnumColourMapperTests-context.xml. Then run the unit test.
Regards,
Sam