首页 > 其他分享 >SpringBoot自定义校验

SpringBoot自定义校验

时间:2024-08-25 08:58:01浏览次数:9  
标签:SpringBoot 自定义 default 校验 注解 ElementType public

通常情况,后端在业务层需要进行大量校验,写在业务层又不美观,而且需要重复编写,很是不方便,Spring提供的校验注解有时无法满足我们的需求,需要自定义校验规则,以校验手机号为例,下面开始自定义校验

一、引入依赖

引入Spring校验依赖包

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

二、定义校验注解

/**
 * 手机号校验注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface PhoneNumber {
    //  校验出错时的提示信息
    String message() default "手机号格式有误";
    //  分组校验
    Class<?>[] groups() default {};
    //  负载属性
    Class<? extends Payload>[] payload() default {};
}
  • @Retention(RetentionPolicy.RUNTIME):代表生效期为代码运行期间

  • @Target({ElementType.FIELD, ElementType.PARAMETER}):代表当前注解可用在类的成员字段上或方法参数上

三、自定义校验器

自定义校验器需压实现 ConstraintValidator<A,V> 接口,A代表注解类型,V代表需要校验值的类型

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
​
/**
 * 电话号码校验器
 */
public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {
    /**
     * 初始化获取注解中的数据
     * @param constraintAnnotation  自定义注解
     */
    @Override
    public void initialize(PhoneNumber constraintAnnotation) {
        //  初始化获取注解中的数据...
    }
​
    /**
     * 定义校验行为
     * @param field 需要校验的字段
     * @param constraintValidatorContext    校验器的上下文环境
     * @return
     */
    @Override
    public boolean isValid(String field, ConstraintValidatorContext constraintValidatorContext) {
        //  电话号码不能为空,且必须满足指定格式
        if (field == null || !field.matches("0?(13|14|15|18|17)[0-9]{9}")) {
            //  不满足要求,校验不通过
            return false;
        }
        //  校验通过
        return true;
    }
}
  • initialize()方法用于开始校验前的校验器初始化操作

  • isValid()方法内部用来自定义校验行为

四、使校验器生效

在自定义校验注解上添加 @Constraint(validatedBy = PhoneNumberValidator.class) 绑定刚刚定义的校验器,如:

/**
 * 手机号校验注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Constraint(validatedBy = {PhoneNumberValidator.class})   //  绑定校验器
public @interface PhoneNumber {
​
    String message() default "手机号格式有误";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
  • @Constraint(validatedBy = {PhoneNumberValidator.class}) :该注解通过validatedBy 属性可以指定多个校验器

完成以上过程即可使用自定义的注解进行校验了

标签:SpringBoot,自定义,default,校验,注解,ElementType,public
From: https://blog.csdn.net/weixin_74261199/article/details/141067760

相关文章