我需要验证POJO,而不必将注释@Valid用作方法的参数。

我被困在这一点上:

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Menu>> constraintViolations=validator.validate(menu);
    //Menu is my Pojo

    if (!constraintViolations.isEmpty()) {
        Iterator itr = constraintViolations.iterator();
        while(itr.hasNext()){
            Object o = itr.next();
        }
    }


似乎可行,因为在“ itr”内部我有类似以下内容:

oConstraintViolationImpl{interpolatedMessage='size must be between 3 and 50', propertyPath=titolo, rootBeanClass=class com.springgestioneerrori.model.Menu, messageTemplate='{javax.validation.constraints.Size.message}'}

现在,我的问题是:如何将“ itr”值添加到BindingResult ???也许我应该投点什么...

谢谢

最佳答案

@Test
public void testBindingResult(BindingResult result,Set<ConstraintViolation<String>> violations){
    for (  ConstraintViolation<String> constraintViolation : violations) {
        ObjectError error=new ObjectError("object",constraintViolation.getMessage());
        result.addError(error);
    }
}


您应该创建类型为ObjectError的对象,here是该类的文档,并将其添加到绑定结果中。

08-04 10:49