2

I have a class similar to this:

public Foo {

  @Valid
  private Bar bar;
  private Long barId;
}

so when I validate class Foo, class Bar is validated as well. But sometimes I don't want class Bar to be validated (eg when it's not possible to correct bad values) when I validate Foo. Can I do something similar to this:

@Valid(when="barId is null")

?

4

1 回答 1

1

实际上,@Valid 中不支持条件。我认为作为一种解决方法,您可以尝试定义您的自定义约束@ConditionalBarValid。您可以在班级级别应用它:

@ConditionalBarValid
public Foo {

    private Bar bar;
    private Long barId;
}

因此,您的约束验证器将可以访问整个 Foo 对象,并且能够:

  • 检查 barId 是否为空
  • 获取 Validator 实例并强制验证bar对象

您的ConditionalBarValidator.isValid(...)实现可能如下所示:

// case when foo is not null and foo.getBarId is null
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
boolean validationResult = validator.validate(foo.getBar()).isEmpty();
于 2013-01-24T18:51:05.273 回答