如何使用注解来校验参数的合法性,像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)方法,目的是初始化正则
到此就可以去测试一下。