【问题标题】:Spring, beans and enum's valueOfSpring、bean 和枚举的 valueOf
【发布时间】:2011-01-25 17:35:01
【问题描述】:

从 Eclipse 调用 Spring 的“Validate”时,当我想使用 Enum 的隐式 "valueOf" 方法取回枚举时,会遇到很多错误。

例如:

<bean id="docFamily" class="...DocFamily" factory-method="valueOf">
    <constructor-arg>
      <value>LOGY</value>
    </constructor-arg>
</bean>

Eclipse 告诉我:

非静态工厂方法'valueOf' 在工厂中找不到 1 个参数 豆类...

但是,据我了解,这是从文档中了解到的:

BeanWrapperImpl 支持 JDK 1.5 枚举 和旧式枚举类:字符串 值将被视为枚举值 名字

所以上面应该可以正常工作吗? (顺便说一句,在这种情况下,'constructor-arg' 是正确的标签,不应该是一些'method-arg'吗?)。

为什么 Eclipse/Spring 的“验证”会给我这个错误消息?

【问题讨论】:

    标签: java spring enums javabeans


    【解决方案1】:

    Enum.valueOf() 有两个参数:

    public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
    

    因此,所需的定义可能如下所示:

    <bean id="docFamily" class="java.lang.Enum" factory-method="valueOf">
         <constructor-arg index = "0"><value>...DocFamily</value></constructor-arg>
         <constructor-arg index = "1"><value>LOGY</value></constructor-arg>
    </bean> 
    

    但是,这样的解决方案可能是更优雅的解决方案:

    <util:constant id = "docFamily" static-field = "...DocFamily.LOGY" />
    

    【讨论】:

    • 我同意,但 OP 并没有尝试使用 java.lang.Enum.valueOf()。我宁愿理解它是 DocFamily.valueOf() 试图被调用。
    • @Grzegorz Oledzki:但 DocFamily 是一个枚举
    【解决方案2】:

    我只是尝试这样使用它:

    <bean id="docFamily" class="...DocFamily" factory-method="valueOf">
        <constructor-arg type="java.lang.String" value="LOGY"/>
    </bean>
    

    它就像魅力一样。对你有用吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多