小王同学
小王同学
发布于 2024-07-08 / 37 阅读
0

设置WebMvcConfig枚举类转换

编写 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非法");
            }
        };
    }
}