【Spring】自定义类型转换器

状态的枚举类

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 {

    @Override
    public  Converter getConverter(Class aClass) {
        return new StringToEnumConverter<>(aClass);
    }

    //将字符串转换成枚举来
    private final class StringToEnumConverter implements Converter {

        private Class enumType;

        public StringToEnumConverter(Class 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());
    }
}

你可能感兴趣的:(【Spring】自定义类型转换器)