Java 如何在Spring中使用enum设置int属性?

Java 如何在Spring中使用enum设置int属性?,java,spring,Java,Spring,我有一个int属性和一个enum。如何在Springbean配置中使用enum设置int属性 public class HelloWorld { private int type1; public void setType1(int type1) { this.type1 = type1; } } public enum MyEnumType1 { TYPE1(1), TYPE2(2); private final int i

我有一个int属性和一个enum。如何在Springbean配置中使用enum设置int属性

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;
    }
}
我尝试了以下方法,但没有成功

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

Spring应用程序上下文:

<util:map id="myMap">
  <entry key="#{T(com.MyEnum).ELEM1}" value="value1" />
  <entry key="#{T(com.MyEnum).ELEM2}" value="value2" />
</util:map>
需要注意的重要事项是,在Spring上下文中,我使用了SpEL(Spring表达式语言),它仅在3.0版之后才可用
@Resource
通过bean名称自动注入值

第页上的答案可以帮助你。看一看

试试看

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

<bean id="helloBean" class="com.example.HelloWorld">
  <property name="type1" value="TYPE1 />
</bean>
public void setType1(MyEnumType1 type1){
this.type1=type1.getIndex();
}


您是否尝试过将MyEnumType1.TYPE1.index
与软件包一起使用?无法猜测
TYPE1
从何而来。一些解释性文字将有助于回答这个问题
public void setType1(MyEnumType1 type1) {
this.type1 = type1.getIndex();
}

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