Spring MVC自动为对象注入枚举数据

一、实现转换工厂,定义转换实现,如下:
 
 
package com.mafwo;

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<?>> {

@Override
public <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;
}

@Override
public 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;
}

     }
 }

  

二、在spring配置文件中配置:
<!--注意在配置转换鼓舞之后需要在 注解驱动处声明-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
<!-- 自动将枚举类型的序列号解析称枚举类型 -->
<bean class="com.mafwo.OrdinalToEnumConverterFactory" />
        </set>
    </property>
</bean>

  

之后就可以使用注解方式自动注入枚举类型数据。

 

posted @ 2016-06-01 11:30  学着总结,学会总结  阅读(624)  评论(0编辑  收藏  举报