1. 编写注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumConstraintValidator.class)
public @interface Enum {
char[] value();
String message() default "对应值非枚举字符属性";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
说明:
- @Target:该注解的作用域,我们仅针对于字段进行使用,所以为:ElementType.FIELD
- @Retention:整个注解的生命周期,填写整个运行时生命周期RetentionPolicy.RUNTIME,不会吃亏的
- @Constraint(validatedBy = EnumConstraintValidator.class):该注解由谁去实现,具体的实现在EnumConstraintValidator类中
- value():存放用户自定义的char枚举值
2.编写validatedBy实现类
public class EnumConstraintValidator implements ConstraintValidator<Enum,Character> {
private char[] verification;
@Override
public void initialize(Enum anEnum) {
verification = anEnum.value();
}
@Override
public boolean isValid(Character value, ConstraintValidatorContext constraintValidatorContext) {
if(verification==null){
return true;
}
for(char c:verification){
if(value ==c){
return true;
}
}
return false;
}
}
说明:
- ConstraintValidator<Enum,Character>:对应的泛型为注解类型和验证字段类型
- initialize():获取对应注解,用户填写的value()信息
- isValid():遍历存储到的verification,如果匹配到则返回true,匹配不到返回false
3. 使用
@Data
@ApiModel("可用性免统计审批DTO")
public class AvailabilityStatisticsFreeApprovalRequestDTO {
@Enum(message = "审批必须为审批通过或者拒绝审批",value = {'1','2'})
@NotNull(message = "审核状态不能为空")
@ApiModelProperty(value = "审核状态:0待审核,1审核通过,2审核拒绝",example = "1")
private Character applyStatus;
}