Haibin Liu
Haibin Liu

Reputation: 610

How to set int property with enum in Spring?

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>

Upvotes: 3

Views: 4945

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

Try as

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

<bean id="helloBean" class="com.example.HelloWorld">
  <property name="type1" value="TYPE1 />
</bean>

Upvotes: 1

Dave Syer
Dave Syer

Reputation: 58124

<bean id="helloBean" class="com.example.HelloWorld">
    <property name="type1" value="#{T(com.MyEnum).TYPE1.index}" />
</bean>

Upvotes: 2

Sunmit Girme
Sunmit Girme

Reputation: 559

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.

Upvotes: 0

Related Questions