枚举所需的实现接口:
public interface BaseIntegerEnum {
Integer getValue();
}
public interface BaseStringEnum {
String getCode();
}
转换器:
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import java.util.HashMap;
import java.util.Map;
public class IntegerCodeEnumConverterFactory implements ConverterFactory<String, BaseIntegerEnum> {
private static final Map<Class, Converter> CONVERTERS = new HashMap<>();
@Override
public <T extends BaseIntegerEnum> Converter<String, T> getConverter(Class<T> targetType) {
Converter<String, T> converter = CONVERTERS.get(targetType);
if (null == converter) {
converter = new IntegerCodeEnumConverter<>(targetType);
CONVERTERS.put(targetType, converter);
}
return converter;
}
public static class IntegerCodeEnumConverter<T extends BaseIntegerEnum> implements Converter<String, T> {
private Map<String, T> enumMap = new HashMap<>();
public IntegerCodeEnumConverter(Class<T> enumType) {
T[] enums = enumType.getEnumConstants();
for (T e : enums) {
enumMap.put(e.getValue().toString(), e);
}
}
@Override
public T convert(String source) {
T t = enumMap.get(source);
if (null == t) {
throw new IllegalArgumentException("No element matches " + source);
}
return t;
}
}
}
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import java.util.HashMap;
import java.util.Map;
public class StringCodeToEnumConverterFactory implements ConverterFactory<String, BaseStringEnum> {
private static final Map<Class, Converter> CONVERTERS = new HashMap<>();
@Override
public <T extends BaseStringEnum> Converter<String, T> getConverter(Class<T> targetType) {
Converter<String, T> converter = CONVERTERS.get(targetType);
if (null == converter) {
converter = new StringToEnumConverter<>(targetType);
CONVERTERS.put(targetType, converter);
}
return converter;
}
public static class StringToEnumConverter<T extends BaseStringEnum> implements Converter<String, T> {
private Map<String, T> enumMap = new HashMap<>();
public StringToEnumConverter(Class<T> enumType) {
T[] enums = enumType.getEnumConstants();
for (T e : enums) {
enumMap.put(e.getCode(), e);
}
}
@Override
public T convert(String source) {
T t = enumMap.get(source);
if (null == t) {
throw new IllegalArgumentException("No element matches " + source);
}
return t;
}
}
}
覆盖addFormatter方法来实现对Converter和ConverterFactory的绑定:
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(new IntegerCodeEnumConverterFactory());
registry.addConverterFactory(new StringCodeToEnumConverterFactory());
}
}