当前位置:网站首页>Personal best practice demo sharing of enum + validation
Personal best practice demo sharing of enum + validation
2022-07-07 17:59:00 【Buffalo calf】
Enum + Validation Personal best practices demo Share
Preface
In many scenarios, we need to verify whether the parameters passed from the front end belong to a Enum value , Share a personal best practice demo:
EnumThe simplest statement of@OfEnum & OfEnumValidatorTest suite
Enum Statement
Usually Enum The declaration of is mapped to the corresponding DB Field , Personal practice is directly based on Enum Name Corresponding to specific value , No need to Enum It contains interpretation information, etc , such as SexEnum Declare as man woman Not like male ("man") Woman ("woman"), This is also convenient for follow-up Validator Class writing
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 " The target value must be ${enumType.simpleName} Enumeration value of type ";
Class<?>[] groups() default {
};
Class<? extends Payload>[] payload() default {
};
}
This annotation is mainly used for fields 、 The corresponding OfEnumValidator Perform verification
@ConstraintAnnotation declaration corresponds toOfEnumValidator- attribute
enumTypeDeclare the corresponding enumeration type messageI quoteELThe expression outputs reasonable verification information
OfEnumValidator
public class OfEnumValidator implements ConstraintValidator<OfEnum, String> {
private List<String> enums;
// Enumeration value initialization
@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 Class is responsible for executing @OfEnum The verification corresponding to the annotation
- Initialize based on the specified enumeration class
enumsattribute , Based on the directtoStringMethod , Therefore, I recommendEnumSimple statement of isValidcheck
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: The target value must be SexEnum Enumeration value of type ");
});
}
}
in the light of @OfEnum Annotated test class :
- be based on
ApplicationContextRunnerTo write , Good test helper class , There was sharing before - You can see , When it comes to
SexEnumValues other than members , A verification exception will be thrown
summary
The above is a person Enum + Validation Best practices sharing
边栏推荐
- Deep learning - make your own dataset
- Click on the top of today's headline app to navigate in the middle
- 仿今日头条APP顶部点击可居中导航
- 基于PyTorch利用CNN对自己的数据集进行分类
- 基于百度飞浆平台(EasyDL)设计的人脸识别考勤系统
- Main work of digital transformation
- 开发一个小程序商城需要多少钱?
- Sanxian Guidong JS game source code
- Simple loading animation
- Face recognition attendance system based on Baidu flying plasma platform (easydl)
猜你喜欢
随机推荐
notification是显示在手机状态栏的通知
ViewSwitcher的功能和用法
[distributed theory] (II) distributed storage
第3章业务功能开发(用户访问项目)
Examen des lois et règlements sur la sécurité de l'information
Chapter 2 building CRM project development environment (building development environment)
Based on pytorch, we use CNN to classify our own data sets
Machine vision (1) - Overview
Interviewer: why is the page too laggy and how to solve it? [test interview question sharing]
【解惑】App处于前台,Activity就不会被回收了?
测试3个月,成功入职 “字节”,我的面试心得总结
漫画 | 宇宙第一 IDE 到底是谁?
Pro2: modify the color of div block
机器人工程终身学习和工作计划-2022-
zdog.js火箭转向动画js特效
如何在软件研发阶段落地安全实践
企业经营12法的领悟
使用OneDNS完美解决办公网络优化问题
原生js验证码
Chapter 3 business function development (user access project)









