Powered By Blogger

Saturday, July 9, 2011

Injecting enums to a map - spring

      Assume an enum class MyEnum is to be used as keys of a java.util.Map and injected in the spring configuration file. This can be done as follows;

package src.shyarmal.eg;

public enum MyEnum {
          A, B, C, D
}

The above enum can be injected to a Map in spring;

<util:map id="myMap" key-type="src.shyarmal.eg.MyEnum">
      <entry key="A" value="value a" />
      <entry key="B" value="value b" />
      <entry key="C" value="value c" />
      <entry key="D" value="value d" />

</util:map>

This map can be injected to a class.

package src.shyarmal.eg;

public class MyClass {

     private Map<MyEnum, String> myMap;

     public void doIt() {
          //do something  ....  
    }
  
    public void setMyMap(Map<MyEnum, String> myMap) {
         this.myMap = myMap;    
   }
}

Spring configuration of MyClass.

<bean id="myClass" class="src.shyarmal.eg.MyClass">
     <property name="myMap" ref="myMap">
</bean>


thanks,
Shyarmal

No comments:

Post a Comment