当前位置:网站首页>Enum + Validation 的个人最佳实践 demo 分享
Enum + Validation 的个人最佳实践 demo 分享
2022-07-07 15:39:00 【小水牛...】
前言
很多场景中我们需要校验前端传来的参数是否属于某个 Enum 值,分享一段个人最佳实践的 demo:
Enum的最简声明@OfEnum & OfEnumValidatorTest suite
Enum 声明
通常 Enum 的声明是映射到对应的 DB 字段,个人实践是直接以 Enum Name 对应具体值,无需在 Enum 里包含释义信息等,比如 SexEnum 声明为 man woman 而不是类似 男("man") 女("woman"),这样也方便后续 Validator 类的编写
public enum SexEnum {
man
, woman
;
}
@OfEnum
@Constraint(
validatedBy = {
OfEnumValidator.class }
)
@Target({
ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface OfEnum {
Class<?> enumType();
String message() default "目标值必须是 ${enumType.simpleName} 类型的枚举值";
Class<?>[] groups() default {
};
Class<? extends Payload>[] payload() default {
};
}
该注解主要用于字段、参数上结合对应的 OfEnumValidator 执行校验
@Constraint注解声明对应的OfEnumValidator- 属性
enumType声明对应的枚举类型 message中引用EL表达式输出合理的校验信息
OfEnumValidator
public class OfEnumValidator implements ConstraintValidator<OfEnum, String> {
private List<String> enums;
// 枚举值初始化
@Override
public void initialize(OfEnum constraintAnnotation) {
enums = Optional.ofNullable(constraintAnnotation)
.map(OfEnum::enumType)
.filter(Class::isEnum)
.map(Class::getEnumConstants)
.map(arr -> Arrays.stream(arr)
.map(Object::toString)
.collect(Collectors.toList()))
.orElse(new ArrayList<>());
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
return !ObjectUtils.isEmpty(enums) && enums.contains(s);
}
}
OfEnumValidator 类负责执行 @OfEnum 注解对应的校验
- 基于指定的枚举类来初始化
enums属性,直接基于toString方法,因此前文推荐Enum的简单声明 isValid进行校验
Test
public class OfEnumTest {
ApplicationContextRunner runner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class));
@Validated
static class Handler {
public void handle(@OfEnum(enumType = SexEnum.class) String sex) {
}
}
static class Config {
@Bean
public Handler handler() {
return new Handler();
}
}
@Test
public void test() {
runner.withUserConfiguration(Config.class)
.run(context -> {
Handler bean = context.getBean(Handler.class);
bean.handle("man");
assertThatThrownBy(() -> bean.handle("error"))
.isInstanceOf(ConstraintViolationException.class)
.hasMessage("handle.sex: 目标值必须是 SexEnum 类型的枚举值");
});
}
}
针对 @OfEnum 注解的测试类:
- 基于
ApplicationContextRunner编写,很好用的测试辅助类,之前有分享 - 可以看到,当传入
SexEnum成员之外的值时,会抛出校验异常
总结
以上就是个人 Enum + Validation 的最佳实践分享
边栏推荐
- LeetCode 1477. Find two subarrays with sum as the target value and no overlap
- Proxmox VE重装后,如何无损挂载原有的数据盘?
- LeetCode 1031. Maximum sum of two non overlapping subarrays
- 智慧物流平台:让海外仓更聪明
- Blue Bridge Cup final XOR conversion 100 points
- 【视频/音频数据处理】上海道宁为您带来Elecard下载、试用、教程
- redis主从、哨兵主备切换搭建一步一步图解实现
- mysql官网下载:Linux的mysql8.x版本(图文详解)
- LeetCode 535(C#)
- DevOps 的运营和商业利益指南
猜你喜欢
随机推荐
With the latest Alibaba P7 technology system, mom doesn't have to worry about me looking for a job anymore
Mrs offline data analysis: process OBS data through Flink job
Pychart ide Download
Siggraph 2022 best technical paper award comes out! Chen Baoquan team of Peking University was nominated for honorary nomination
DNS series (I): why does the updated DNS record not take effect?
Several best practices for managing VDI
LeetCode 890(C#)
LeetCode 1155. N ways to roll dice one question per day
LeetCode 213. Home raiding II daily question
A tour of grpc:03 - proto serialization / deserialization
Shallow understanding Net core routing
LeetCode 1626. The best team without contradiction
LeetCode1051(C#)
无法链接远程redis服务器(解决办法百分百)
Rpcms method of obtaining articles under the specified classification
MySQL implements the query of merging two fields into one field
LeetCode 1981. Minimize the difference between the target value and the selected element one question per day
On Apache Doris Fe processing query SQL source code analysis
L1-019 谁先倒(Lua)
Reflections on "product managers must read: five classic innovative thinking models"




![[image sensor] correlated double sampling CDs](/img/1c/3a641ad47ff91536db602dedc82705.png)




