当前位置:网站首页>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
边栏推荐
- 做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
- Five simple ways to troubleshoot with Stace
- 带动画的列表选中js特效
- 企业经营12法的领悟
- Please insert the disk into "U disk (H)" & unable to access the disk structure is damaged and cannot be read
- [OKR target management] case analysis
- Deep learning - make your own dataset
- swiper左右切换滑块插件
- VSCode关于C语言的3个配置文件
- DatePickerDialog和trimepickerDialog
猜你喜欢
【重新理解通信模型】Reactor 模式在 Redis 和 Kafka 中的应用
Robot engineering lifelong learning and work plan-2022-
第3章业务功能开发(用户登录)
[deep learning] 3 minutes introduction
【深度学习】3分钟入门
Function and usage of textswitch text switcher
Mobile app takeout ordering personal center page
企业经营12法的领悟
Taffydb open source JS database
面试官:页面很卡的原因分析及解决方案?【测试面试题分享】
随机推荐
Introduction to OTA technology of Internet of things
保证接口数据安全的10种方案
Mobile app takeout ordering personal center page
【解惑】App处于前台,Activity就不会被回收了?
Hutool - 轻量级 DB 操作解决方案
Numberpick的功能和用法
Define menus using XML resource files
Mysql 索引命中级别分析
Native JS verification code
[OKR target management] value analysis
Slider plug-in for swiper left and right switching
zdog. JS rocket turn animation JS special effects
TabHOST 选项卡的功能和用法
【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题
深入浅出图解CNN-卷积神经网络
cf:C. Factorials and Powers of Two【dp + 排序 + 选不选板子 + 选若干个数等于已知和的最少数】
Yarn capacity scheduler (ultra detailed interpretation)
目标管理【管理学之十四】
Youth experience and career development
Functions and usage of ratingbar