【问题标题】:Injecting an enum with Spring使用 Spring 注入枚举
【发布时间】:2015-12-12 01:43:51
【问题描述】:

我正在尝试使用 <util:constant 通过 spring 上下文注入 java 枚举。

这就是我所做的。在我的 spring 配置中,我有以下条目

<util:constant id="Content" static-field="com.test.taxonomy.model.MetadataTypeEnum.CONTENT_GROUP" />
<util:constant id="Category" static-field="com.test.taxonomy.model.MetadataTypeEnum.CATEGORY" />   

<bean id="ADSKContentGroup" class="com.test.taxonomy.model.ADSKContentGroup" scope="prototype">
  <property name="name" ref="Content" /> 
</bean>

在这里,我试图利用枚举 ADSKContentGroup 注入到我的 bean 的 (ADSKContentGroup) ame 属性中。

这是枚举:

public enum MetadataTypeEnum {
  CONTENT_GROUP ("ADSKContentGroup"),

  private String metadataType;

  private MetadataTypeEnum(String metadataType) {
    this.metadataType = metadataType;
  }
  public String getMetadataType() {
    return this.metadataType;
  }
}

这是豆子:

public class ADSKContentGroup extends Metadata {
  public ADSKContentGroup(){
  }
}

bean 扩展自一个基类,该基类具有 name 属性的设置器

这是类定义:

public class Metadata {
  private MetadataTypeEnum name;
  private String value;

  public String getName() {
    return name.getMetadataType();
  }

  public void setName(MetadataTypeEnum name) {
    this.name = name;
  }
}

在运行时,我得到以下异常

ERROR com.test.taxonomy.plugin.TaxonomyPluginImpl  - Error in creating metadata mapping :Error creating bean with name 'ADSKContentGroup' defined in ServletContext resource [/WEB-INF/beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [com.test.taxonomy.model.MetadataTypeEnum] to required type [java.lang.String] for property 'name'; nested exception is java.lang.IllegalArgumentException: Original must not be null  
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ADSKContentGroup' defined in ServletContext resource [/WEB-INF/beans.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [com.test.taxonomy.model.MetadataTypeEnum] to required type [java.lang.String] for property 'name'; nested exception is java.lang.IllegalArgumentException: Original must not be null

不确定我的方法出了什么问题。

高度赞赏任何指针。

  • 谢谢

【问题讨论】:

  • 什么版本的java和什么版本的spring

标签: java spring enums


【解决方案1】:

您的Metadata 类是设计不良的JavaBean,它不符合规范:setter 使用MetadataTypeEnum 类型的参数,但getter 的返回类型是String。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2013-06-19
    相关资源
    最近更新 更多