一、定义一个注解
/**
* @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 {};
}
这个注解是作用在Menthod或者Field字段上,运行时生效,触发的是LoanValidate这个验证类。
- message 定制化的提示信息,主要是从ValidationMessages.properties里提取,也可以依据实际情况进行定制
- groups 这里主要进行将validator进行分类,不同的类group中会执行不同的validator操作
- payload 主要是针对bean的,使用不多。
二、编写实现注解的实现
/**
* @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;
}