如何强制Hibernate Validator以递归方式验证字段(级联)?

时间:2015-11-30 20:51:59

标签: java bean-validation hibernate-validator

我有以下型号:

class EmailWrapper {

    @Email
    private String subscriptionEmail;

    private MyClass myClass;
    //get and set
}


class MyClass {
    @Size(min = 12)
    private String str = "short";
    //get and set
}

以下代码:

EmailWrapper emailWrapper = new EmailWrapper();
emailWrapper.setSubscriptionEmail("qq@gmail.com");
emailWrapper.setMyClass(new MyClass());
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<EmailWrapper>> constraintViolations = validator.validate(emailWrapper);
System.out.println(constraintViolations.size());

您可以看到emailWrapper.myClass.str违反了@Size(min = 12)

但我在控制台中看到0。如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

替换

private MyClass myClass;

通过

@Valid
private MyClass myClass;