一、枚举类型
1、枚举的声明和定义:
枚举类型是这样的,
public interface BaseEnum { Integer getCode(); String getText(); }
继承自该接口的枚举类,
@AllArgsConstructor @Getter public enum CollectionOrNot implements BaseEnum { NO(0, "否"), YES(1, "是"); private Integer code; @JsonValue private String text; @JsonCreator public static CollectionOrNot jsonCreate(Integer code) { return EnumUtils.codeOf(CollectionOrNot.class, code); } @JsonCreator public static CollectionOrNot jsonCreate(String text) { return EnumUtils.codeOf(CollectionOrNot.class, text); } }
EnumUtils的代码:
public class EnumUtils { public static <T extends BaseEnum> T codeOf(Class<T> enumClass, int code) { T[] enumConstants = enumClass.getEnumConstants(); for (T t : enumConstants) { if (t.getCode() == code) { return t; } } return null; } public static <T extends BaseEnum> T codeOf(Class<T> enumClass, String text) { T[] enumConstants = enumClass.getEnumConstants(); for (T t : enumConstants) { if (t.getText().equals(text)) { return t; } } return null; } }
2、ConverterFactory的声明和定义,
import com.tianji.tingcloudapi.common.enums.BaseEnum; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; public class StringToEnumConverterFactory implements ConverterFactory<String, BaseEnum> { private static class StringToEnumConverter<T extends BaseEnum> implements Converter<String, T> { private Class<T> enumType; // 构造方法 public StringToEnumConverter(Class<T> enumType) { this.enumType = enumType; } public T convert(String source) { T[] enumConstants = enumType.getEnumConstants(); for (T t : enumConstants) { if (t.getText().equals(source)) return t; } throw new IllegalArgumentException("无法匹配对应的枚举类型"); } } @Override public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) { return new StringToEnumConverter<>(targetType); } }
3、ConverterFactory的注册
@Configuration public class WebMvcConfig implements WebMvcConfigurer { /** * 枚举类的转换器工厂 addConverterFactory */ @Override public void addFormatters(FormatterRegistry registry) { // registry.addConverterFactory(new IntegerToEnumConverterFactory()); registry.addConverterFactory(new StringToEnumConverterFactory()); } }
4、参数绑定
@RequestParam(name = "cpuGatherState", required = false) CollectionOrNot cpuGatherState,
5、相关链接
- Using Enums as Request Parameters in Spring
- Guide to Spring Type Conversions
- Spring Boot 使用枚举类型作为请求参数
二、JSR310的日期绑定