自定义注解
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)