自定义javax.validation 校验能用 spring

自定义注解

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;


@Target(ElementType.FIELD)
@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {
        IdExistMyTestValidator.class
})
public @interface IdExistMyTest {

    //如果出错,返回的数据
    String message() default "id数据不匹配";

    boolean required() default false;

    // 环境区分,一般用<接口.class>来区分
    Class<?>[] groups() default {};

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

}

service相关自定义校验父类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.util.Objects;
import java.util.function.Predicate;

@Slf4j
public class MyTestValidator<A extends Annotation,T> implements ConstraintValidator<A, T> {

    // 是否强制校验
    protected boolean required;

    // 默认值直接通过
    protected Predicate<T> isValidFunc = t -> true;

    @Autowired
    protected IMyTestService service;

    //进行校验的逻辑判断
    @Override
    public boolean isValid(T t, ConstraintValidatorContext constraintValidatorContext) {
        if(!required && Objects.isNull(t)){
            return true;
        }
        return isValidFunc.test(t);
    }
}

自定义校验具体实现

public class IdExistMyTestValidator extends MyTestValidator<IdExistMyTest,String>{

    //初始化传入的是注解
    //进行校验的逻辑判断
    @Override
    public void initialize(IdExistMyTest constraintAnnotation) {
        // t接收的参数
        isValidFunc = t ->{
            final long count = service.count(
                    new LambdaQueryWrapper<MyTest>()
                            .eq(MyTest::getTestId, t)
            );
            return count != 0;
        };
        this.required = constraintAnnotation.required();
        super.initialize(constraintAnnotation);
    }
}

自定义注解对象里使用

MyTestRO

    /** 主键 */
    @ApiModelProperty(value = "主键" )
    @NotEmpty(message = "主键不为空")
    @IdExistMyTest(groups =GroupA.class )
    @Length(max = 32,message = "主键长度不超过32")
    private String testId;

    public interface GroupA {
    }
    public interface GroupB {
    }
    // 组序列 ,简单控制校验顺序
    @GroupSequence({Default.class, GroupA.class, GroupB.class})
    public interface Group {
    }

POST请求调用自定义校验

@RequestBody @Validated(MyTestRO.Group.class)
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值