【问题标题】:How to use Spring to get the value of an Enum如何使用 Spring 获取 Enum 的值
【发布时间】:2010-11-09 19:59:09
【问题描述】:
<bean id="xyz" class="com.abc" >
  <property name="name">
    <bean         
            class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
        <property name="staticField" value="com.abc.staticname" />
     </bean>
   </property>
</bean>

这是我之前设置类 com.abc 的名称的方式。现在,名称应该来自另一个枚举。如何访问枚举值以设置我的类 com.abc 的名称属性?

【问题讨论】:

    标签: java spring enums


    【解决方案1】:

    我不明白你为什么不能继续使用FieldRetrievingFactoryBean,这就是它的用途。

    不过,它比您的示例所建议的更容易使用。此外,还有更简单的基于模式的语法&lt;util:constant&gt;

    这两种方法都有记录(并比较)here

    (请记住,枚举值只是枚举类上的静态字段)

    【讨论】:

    • 谢谢,这个链接很有帮助。
    【解决方案2】:

    你可以只使用枚举名称作为值,Spring会自动检测到它是枚举类型的静态字段并使用它。例如,如果您有一个枚举 com.mycompany.MyEnum,其值为 SOMEVAL、AN​​OTHERVAL,您可以使用:

    <property name="myEnumProperty" value="SOMEVAL" />
    

    这将允许您完全避免 FieldRetrievingFactoryBean 和 &lt;util:constant&gt;

    【讨论】:

      猜你喜欢
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多