如何 java bean 仅在非空或零时验证范围

How to java bean validate range only if not null or zero

我想使用 Java Bean Validation 来验证一个整数。 是多次验证的验证。

我目前正在使用 Spring 引导和验证,并且系统正在使用 @RestController 我正在接收 post 呼叫。

public Person addPerson(@RequestBody @Validated Person Person) {/*the code*/}

我希望验证年龄,这些值有效:

age == null or age == 0 or (age >= 15 and age <= 80)


public class Person {
    private Integer age;
}

我希望能够使用 java 的当前验证约束。 我需要实现自己的约束注解吗?

这很好,但这不起作用:

public class Person {
    @Null
    @Range(min=0, max=0)
    @Range(min=15, max = 80)
    private Integer age;
}

根据 Implementing Validation for RESTful Services with Spring Boot,正确的注释是 @Valid(而不是 @Validated

您可以使用 ConstraintCoposition 对约束进行分组:

public class Test {

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    @ConstraintComposition(CompositionType.AND)
    @Min(value = 0)
    @Max(value = 0)
    @Target( { ElementType.ANNOTATION_TYPE } )
    @Retention( RetentionPolicy.RUNTIME )
    @Constraint(validatedBy = { })
    public @interface ZeroComposite {
        String message() default "Not valid";
        Class<?>[] groups() default { };
        Class< ? extends Payload>[] payload() default { };
    }

    @ConstraintComposition(CompositionType.OR)
    @Null
    @ZeroComposite
    @Range(min=15, max = 80)
    @Target( { ElementType.METHOD, ElementType.FIELD } )
    @Retention( RetentionPolicy.RUNTIME )
    @Constraint(validatedBy = { })
    public @interface Composite {
        String message() default "Not valid";
        Class<?>[] groups() default { };
        Class< ? extends Payload>[] payload() default { };
    }

    @Composite
    private Integer age;


    public Test(Integer age) {
        this.age = age;
    }

    public static void main(String args[]) {
        validate(new Test(-1));
        validate(new Test(null));
        validate(new Test(0));
        validate(new Test(5));
        validate(new Test(15));
        validate(new Test(80));
        validate(new Test(81));
    }

    private static void validate(Test t) {
        Set<ConstraintViolation<Test>> violations = 
            factory.getValidator().validate(t);

        for (ConstraintViolation<Test> cv : violations) {
            System.out.println(cv.toString());
        }
    }
}