编写 config 类
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private StringToBaseEnumConverterFactory factory;
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(this.factory);
}
}
注册config类
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
@Override
public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
return new Converter<String, T>() {
@Override
public T convert(String code) {
for (T typeEnumConstant : targetType.getEnumConstants()) {
if (typeEnumConstant.getCode().equals(Integer.valueOf(code))){
return typeEnumConstant;
}
}
throw new IllegalArgumentException("code非法");
}
};
}
}