1. Implement the conversion factory and define the conversion implementation, as follows:
package com.mafwo;Second, configure in the spring configuration file:
import org.springframework.core.convert.converter.Converter;import org.springframework.core.convert.converter.ConverterFactory;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class OrdinalToEnumConverterFactory implements ConverterFactory<String, Enum<?>> {@Overridepublic <T extends Enum<?>> Converter<String, T> getConverter(Class<T> targetType) {
return new OrdinalToEnum<T>(targetType);
}
private class OrdinalToEnum<T extends Enum<?>> implements Converter<String, T> {
private final Class<T> enumType;
public OrdinalToEnum(Class<T> enumType) {this.enumType = enumType;}@Overridepublic T convert(String source) {// 转换成数字int ordinal = Integer.valueOf
(source);
if(ordinal == Integer.MIN_VALUE) {
return null;
}
Object temp = null;
try {
Method getCode = enumType.getMethod("getCode");
Object[] objects = enumType.getEnumConstants();
for(Object ob: objects){
Integer temps = (Integer) getCode.invoke(ob);
if(temps == ordinal)
{
temp = ob;
break;
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return (T) temp;
}
}
}
<!-- Note that it needs to be declared at the annotation-driven place after configuring conversion incentives -->After that, you can use annotations to automatically inject enumeration type data.
< mvc :annotation-driven conversion-service = "conversionService" ></ mvc :annotation-driven>
<bean id = "conversionService" class = "org.springframework.context.support.ConversionServiceFactoryBean" > <property name ="converters" > <set> <!-- Automatically resolve the serial number of the enumeration type to the enumeration type --> <bean class ="com. mafwo.OrdinalToEnumConverterFactory" /> </set> </property> </bean>