Spring接收枚举类型

目录

    • json
    • form表单

json

  1. spring容器注入如下Bean,ObjectMapper注入WRITE_ENUMS_USING_TO_STRING
 @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer(){
        return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    }
  1. 枚举类中重写toString
public enum SexType {

    BOY("1","男"),
    GIRL("2","女");
    private String code;
    private String sex;

    @Override
    public String toString() {
        return code;
    }
}

form表单

  1. 实现类型转换器
@Component
public class CustomerConverter implements Converter<String, SexType> {

    @Override
    public SexType convert(String source) {
        for(SexType sexType : SexType.values()) {
            if(sexType.getCode().equals(source)) {
                return sexType;
            }
        }
        return null;
    }
}

或者

1.定义ConverterFactory

@Component
public class ConsumerConverterFactory  implements ConverterFactory<String, IBaseEnum> {
    @Override
    public Converter getConverter(Class targetType) {

        return new BaseConverter(targetType);
    }

    class BaseConverter<T extends IBaseEnum> implements Converter<String, T> {

        private Class<T> enumType;
        private Map<String, T> enumMap = new HashMap<>();

        public BaseConverter(Class<T> enumType) {
            this.enumType = enumType;
        }


        @Override
        public T convert(String source) {
            for(IBaseEnum sexType : enumType.getEnumConstants()) {
                if(sexType.getValue().equals(source)) {
                    return (T) sexType;
                }
            }
            return null;
        }
    }
}
  1. springboot 整合
@Configuration
public class ConsumWebMvcConfig  implements WebMvcConfigurer{

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(new ConsumerConverterFactory());
    }
}

你可能感兴趣的:(spring)