【问题标题】:How to java bean validate range only if not null or zero仅当非空或零时,Java bean 才验证范围
【发布时间】:2018-09-21 09:38:25
【问题描述】:

我想使用 Java Bean Validation 来验证 Integer。 它是多个验证的验证。

我目前正在使用 Spring Boot 和验证,系统正在使用 @RestController 我正在接收 post-call。

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;
}

【问题讨论】:

  • 你能解释一下你所说的“不起作用”是什么意思吗?您在什么时候运行验证?您使用的是哪个验证框架?你遇到了什么问题?

标签: java validation bean-validation validationrules


【解决方案1】:

您可以使用 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());
        }
    }
}

【讨论】:

  • 谢谢,这是完美的。请在验证方法中添加ValidatorFactory factory = Validation.buildDefaultValidatorFactory();。那么这将被选为正确答案。
  • 对,应该定义为静态字段。当我复制代码时它丢失了。
【解决方案2】:

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

【讨论】:

  • 可以,不过按照这个link没关系。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 2016-11-26
相关资源
最近更新 更多