自定义注解实现对字段的取值范围校验
作者:互联网
一、定义一个注解
/**
* @description: 自定义个注解,用于校验字符串类型的数据是否在指定的范围内
* @author:zhanghuazheng
* @createTime:2021/2/4 15:53
* @version:1.0
*/
@Documented
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { LoanValidate.class})
public @interface FiledEnumRule {
String[] in() default "";
String message() default "{javax.validation.constraints.NotEmpty.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
二、编写实现注解的实现
/**
* @description:
* @author:zhanghuazheng
* @createTime:2021/2/4 15:51
* @version:1.0
*/
@Slf4j
public class LoanValidate implements ConstraintValidator<FiledEnumRule, String> {
private String[] filedValues = {};
@Override
public boolean isValid(String input, ConstraintValidatorContext constraintValidatorContext) {
log.info("数据校验入参args=" + input);
List<String> list = Arrays.asList(filedValues);
if(list.contains(input)){
return true;
}
return false;
}
@Override
public void initialize(FiledEnumRule constraintAnnotation) {
filedValues = constraintAnnotation.in();
log.info("数据校验入参args=" + filedValues);
}
}
三、具体使用
/**
* @description: 贷款申请信息内部转换模型
* @author:zhanghuazheng
* @createTime:2021/1/29 20:16
* @version:1.0
*/
@Data
@Validated
public class CustomerInfo implements Serializable {
private static final long serialVersionUID = 1L;
@NotEmpty(message = "nationality can not empty")
@Length(max = 8, message = "nationality 长度不符合要求")
@FiledEnumRule(in={"CHN","JAP","AMR"},message = "数据不在定义范围内")
private String nationality;
@NotEmpty(message = "applyTime can not empty")
@Length(max = 19, message = "applyTime 长度不符合要求")
private String applyTime;
@NotEmpty(message = "purposeOfAccount can not empty")
@Length(max = 128, message = "purposeOfAccount 长度不符合要求")
private String purposeOfAccount;
}
标签:String,自定义,default,NotEmpty,校验,private,message,public,对字 来源: https://blog.csdn.net/zhz1605/article/details/113655207