業務場景:前端提交了枚舉的一個屬性value,想由spring來完成參數類型自動轉換成對應的枚舉。前端
比方有一個枚舉ajax
@AllArgsConstructor(access = AccessLevel.PRIVATE) @Getter @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum RegisterStatus implements SpringConverterableEnum { WAITING(0, "待審覈"), PASSED(1, "已經過"), REJECTED(2, "已拒絕"); private int value; private String desc; }
須要自動轉換的枚舉實現統一自定義接口,可隨意定義,此處直接用get方法spring
public interface SpringConverterableEnum { int getValue(); }
實現某一個class的類型自動轉換,實現converter接口。要實現能支持多種枚舉的通用轉換,應當實現ConverterFactory接口。mvc
實現中利用class提供的getEnumConstants來得到任意枚舉類型的valueside
public class ValuedEnumConverter implements ConverterFactory<String, SpringConverterableEnum> { @Override public <T extends SpringConverterableEnum> Converter<String, T> getConverter(Class<T> targetType) { return new IntegerToEnum(targetType); } private class IntegerToEnum<T extends SpringConverterableEnum> implements Converter<String, T> { private final T[] values; public IntegerToEnum(Class<T> targetType) { values = targetType.getEnumConstants(); } @Override public T convert(String source) { for (T t : values) { if (t.getValue() == Integer.valueOf(source)) { return t; } } return null; } } }
<mvc:annotation-driven conversion-service="conversionService"/> <bean class="org.springframework.context.support.ConversionServiceFactoryBean" id="conversionService"> <property name="converters"> <list> <bean class="com... ValuedEnumConverter"/> </list> </property> </bean>
以後,form或者ajax提交registerStatus=1時,則會自動轉換爲枚舉對象。spa