Springboot中如何自定义参数校验注解

如何使用注解来校验参数的合法性,像spring-boot-starter-validation中的校验注解一样,不符合校验规则直接抛出BindException异常。

一、添加maven

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

二、首先定义校验注解,这里我们以车牌为例。需要在注解中添加@Constraint(validatedBy = LicensePlateValidator.class),LicensePlateValidator.class为处理此注解校验逻辑的类

/**
 * 车牌号校验注解
 * @author hmh
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = LicensePlateValidator.class)
public @interface LicensePlate {
    String message() default "车牌号格式错误";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

三、新建LicensePlateValidator.class类并实现ConstraintValidator接口,实现isValid(String s, ConstraintValidatorContext constraintValidatorContext)方法,isValid方法为主要逻辑实现

public class LicensePlateValidator implements ConstraintValidator<LicensePlate, String> {
    private Pattern oilPattern;
    private Pattern elePattern;

    @Override
    public void initialize(LicensePlate constraintAnnotation) {
        elePattern = Pattern.compile("^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(?!(?:.*[A-Z]){3})[A-Z0-9]{5}$|^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-F]{1}(?!(?:.*[A-Z]){3})[A-Z0-9]{5})$");
        oilPattern = Pattern.compile("^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}(?!(?:.*[A-Z]){3})[A-Z0-9]{5}$");
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (Func.isBlank(s)) {
            return false;
        }

        return oilPattern.matcher(s).matches() || elePattern.matcher(s).matches();
    }
}

这里我实现了initialize(LicensePlate constraintAnnotation)方法,目的是初始化正则

到此就可以去测试一下。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值