自定义注解实现对字段的取值范围校验

一、定义一个注解

/**
 * @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;
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值