当前位置:网站首页>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
:
Enum
The simplest statement of@OfEnum & OfEnumValidator
Test 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
@Constraint
Annotation declaration corresponds toOfEnumValidator
- attribute
enumType
Declare the corresponding enumeration type message
I quoteEL
The 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
enums
attribute , Based on the directtoString
Method , Therefore, I recommendEnum
Simple statement of isValid
check
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
ApplicationContextRunner
To write , Good test helper class , There was sharing before - You can see , When it comes to
SexEnum
Values other than members , A verification exception will be thrown
summary
The above is a person Enum + Validation
Best practices sharing
边栏推荐
猜你喜欢
YARN Capacity Scheduler容量调度器(超详细解读)
JS pull down the curtain JS special effect display layer
swiper左右切换滑块插件
Toast will display a simple prompt message on the program interface
使用OneDNS完美解决办公网络优化问题
数学分析_笔记_第11章:Fourier级数
Taffydb open source JS database
mui侧边导航锚点定位js特效
Please insert the disk into "U disk (H)" & unable to access the disk structure is damaged and cannot be read
VSCode关于C语言的3个配置文件
随机推荐
Face recognition attendance system based on Baidu flying plasma platform (easydl)
Toast will display a simple prompt message on the program interface
使用OneDNS完美解决办公网络优化问题
Sanxian Guidong JS game source code
物联网OTA技术介绍
Dateticket and timeticket, functions and usage of date and time selectors
【OKR目标管理】价值分析
What skills can you master to be a "master tester" when doing software testing?
imageswitcher的功能和用法
Mysql 索引命中级别分析
什么是敏捷测试
做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
Functions and usage of imageswitch
Chapter 3 business function development (user login)
手机app外卖订餐个人中心页面
Run Yolo v5-5.0 and report an error. If the sppf error cannot be found, solve it
Actionbar navigation bar learning
第1章CRM核心业务介绍
使用popupwindow創建对话框风格的窗口
mui侧边导航锚点定位js特效