【Spring】自定义类型转换器
2018-04-30 本文已影响25人
eejron
状态的枚举类
public enum State implements IEnum{
enabled(0,"正常"),
disabled(1,"已注销"),
risk(2,"风险")
;
private final Integer value;
private final String display;
State( Integer value, String display) {
this.value = value;
this.display = display;
}
@Override
public String getByName() {
return name();
}
}
现在我希望当前端通过如下接口传递"test/state?state=enabled"参数的时候,可以获取到状态对应的枚举
@RequestMapping("test/state")
public String testEnum(State state){
//todo
return "";
}
那么我们需要做做如下代码实现
public class StringToEnumConverterFactory implements ConverterFactory<String, IEnum> {
@Override
public <T extends IEnum> Converter<String, T> getConverter(Class<T> aClass) {
return new StringToEnumConverter<>(aClass);
}
//将字符串转换成枚举来
private final class StringToEnumConverter<T extends IEnum> implements Converter<String, T> {
private Class<T> enumType;
public StringToEnumConverter(Class<T> enumType) {
this.enumType = enumType;
}
@Override
public T convert(String s) {
for (T t : enumType.getEnumConstants()) {
if (t.getByName().equals(s)) {
return t;
}
}
return null;
}
}
}
同时把这个处理器注册到Spring的容器中即可
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(new StringToEnumConverterFactory());
}
}