当前位置:网站首页>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
边栏推荐
- 【OKR目标管理】案例分析
- Functions and usage of imageswitch
- Deep learning machine learning various data sets summary address
- What is agile testing
- 物联网OTA技术介绍
- Supplementary instructions to relevant rules of online competition
- Pytorch中自制数据集进行Dataset重写
- Chapter 2 building CRM project development environment (building development environment)
- List selection JS effect with animation
- 【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题
猜你喜欢
随机推荐
List selection JS effect with animation
自动化测试:Robot FrameWork框架大家都想知道的实用技巧
In depth understanding of USB communication protocol
Tips for this week 131: special member functions and ` = Default`
漫画 | 宇宙第一 IDE 到底是谁?
DatePickerDialog和trimepickerDialog
2021-06-28
textSwitch文本切换器的功能和用法
目标检测1——YOLO数据标注以及xml转为txt文件脚本实战
[distributed theory] (II) distributed storage
做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
[distributed theory] (I) distributed transactions
Audio device strategy audio device output and input selection is based on 7.0 code
cf:C. Factorials and Powers of Two【dp + 排序 + 选不选板子 + 选若干个数等于已知和的最少数】
Dateticket and timeticket, functions and usage of date and time selectors
4种常见的缓存模式,你都知道吗?
< code random recording two brushes> linked list
仿今日头条APP顶部点击可居中导航
Actionbar navigation bar learning
如何在软件研发阶段落地安全实践









