Injecting an enum with Spring
I'm trying to inject java enum through spring context using <util:constant
.
Here's what I've done. In my spring config, I've following entry
<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>
Here, I'm trying to leverage an Enum ADSKContentGroup to be injected in my bean's (ADSKContentGroup) ame property.
Here's the enum :
public enum MetadataTypeEnum {
CONTENT_GROUP ("ADSKContentGroup"),
private String metadataType;
private MetadataTypeEnum(String metadataType) {
this.metadataType = metadataType;
}
public String getMetadataType() {
return this.metadataType;
}
}
Here's the bean :
public class ADSKContentGroup extends Metadata {
public ADSKContentGroup(){
}
}
The bean extends from a base class which has the setter for name attribute
Here's the class definition:
public class Metadata {
private MetadataTypeEnum name;
private String value;
public String getName() {
return name.getMetadataType();
}
public void setName(MetadataTypeEnum name) {
this.name = name;
}
}
In runtime, I'm getting the following exception
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 excepti开发者_开发百科on is java.lang.IllegalArgumentException: Original must not be null
Not sure what's going wrong with my approach.
Any pointer is highly appreciated.
- Thanks
Your Metadata
class is ill-designed JavaBean, it does not conform to the spec: The setter uses a parameter of type MetadataTypeEnum
, but the return type of the getter is String
.
精彩评论