Validator校验

洪高刚
2023-12-01

自定义Validator校验

定义校验注解 


@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValueValidator.class})
public @interface EnumValue {
    // 默认错误消息
    String message() default "必须为指定值";

    String[] strValues() default {};

    int[] intValues() default {};

    long[] longValues() default {};

    // 分组
    Class<?>[] groups() default {};

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

    // 指定多个时使用
    @Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        EnumValue[] value();
    }
}

定义校验器 

public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
    private String[] strValues;
    private int[] intValues;
    private long[] longValues;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
        longValues = constraintAnnotation.longValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (int s : intValues) {
                if (s == (Integer) value) {
                    return true;
                }
            }
        } else if (value instanceof Long){
            for (long s : longValues) {
                if (s == (Long) value) {
                    return true;
                }
            }
        }
        return false;
    }
}

使用

    @EnumValue(longValues = {0,1},message = "付款方式错误")
    private Long orderType;

级联校验

public class A{

    @Valid
    @NotNull(message = "b不能为空")
    @Size(min = 1, message = "b不能为空")
    private List<B> b;

    public static class B{
        @NotNull(message = "tenantId not null")
        private Long tenantId;
    }
}


public class XxxController {

    @PostMapping("/xxx")
    public xxx xxx(@RequestBody @Validated A a) {
       
    }
}

 类似资料: