背景
官方提供的注解多数可以解决现实业务场景中基本业务校验,但有些特殊场景因业务的复杂性,也还是需要在入口处对入参进行各种角度的校验,以求简化业务层的处理,降低业务处理复杂性与方法入口的强约束性。 以上背景,下面就举个简单Demo进行自定义注解校验的实现。
注解定义类
1 import javax.validation.Constraint; 2 import javax.validation.Payload; 3 import java.lang.annotation.ElementType; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 import java.lang.annotation.Target; 7 8 /** 9 * @author wpp 10 * @date 2020/8/22 14:30 11 */ 12 @Target({ElementType.FIELD, ElementType.METHOD}) 13 @Retention(RetentionPolicy.RUNTIME) 14 @Constraint(validatedBy = PhoneCustomizeValidator.class) 15 public @interface CustomizeValidator { 16 17 String message() default "不是国内手机号"; 18 19 Class<?>[] groups() default {}; 20 21 Class<? extends Payload>[] payload() default {}; 22 23 }
注解方法处理类
import cn.hutool.core.util.StrUtil; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.regex.Pattern; /** * @author wpp * @date 2020/8/22 14:33 */ public class PhoneCustomizeValidator implements ConstraintValidator<CustomizeValidator, String> { private String phoneRegex = "^(16[0-9]|19[0-9]|13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$"; private Pattern phonePattern = Pattern.compile(phoneRegex); @Override public void initialize(CustomizeValidator constraintAnnotation) { } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (StrUtil.isBlank(value)) { return Boolean.FALSE; } return phonePattern.matcher(value).matches(); } }
使用方式
import io.swagger.annotations.ApiModelProperty; import lombok.Builder; import lombok.Data; import org.hibernate.validator.constraints.Length; /** * @author wpp * @date 2020/8/22 14:49 */ @Data @Builder public class CustomizeDTO { @ApiModelProperty(name = "phone", value = "手机号码") @Length(max = 13) private String phone; }