3

I have a property of int and I have an enum. How can I set the int property using the enum in Spring bean configuration?

public class HelloWorld {
    private int type1;

    public void setType1(int type1) {
        this.type1 = type1;
    }
}

public enum MyEnumType1 {
    TYPE1(1),
    TYPE2(2);

    private final int index;

    private MyEnumType1(int i) {
        this.index = i;
    }

    public int getIndex() {
        return index;
    }
}

I tried the following but did not work.

<bean id="helloBean" class="com.example.HelloWorld">
    <property name="type1" value="TYPE1.index" />
</bean>
Haibin Liu
  • 610
  • 1
  • 7
  • 18
  • 1
    Have you tried using `MyEnumType1.TYPE1.index` along with package? There is no way to guess where `TYPE1` comes from. – Bhesh Gurung Nov 28 '12 at 06:05

3 Answers3

2
<bean id="helloBean" class="com.example.HelloWorld">
    <property name="type1" value="#{T(com.MyEnum).TYPE1.index}" />
</bean>
Dave Syer
  • 56,583
  • 10
  • 155
  • 143
1

Try as

public void setType1(MyEnumType1 type1) {
this.type1 = type1.getIndex();
}

<bean id="helloBean" class="com.example.HelloWorld">
  <property name="type1" value="TYPE1 />
</bean>
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Spring application context:

<util:map id="myMap">
  <entry key="#{T(com.MyEnum).ELEM1}" value="value1" />
  <entry key="#{T(com.MyEnum).ELEM2}" value="value2" />
</util:map>

Class where the Map gets injected:

public class MyClass {

    private @Resource Map<MyEnum, String> myMap;
}

The important things to note are that in the Spring context I used SpEL (Spring Expression Language) which is only available since version 3.0. @Resource auto-injects the values by bean name.

The answers on this page can help you. Have a look at it.

Community
  • 1
  • 1
Sunmit Girme
  • 559
  • 4
  • 13
  • 30