Bean验证多个属性节点

时间:2017-06-29 10:46:09

标签: spring annotations javabeans bean-validation null-pointer

我正在使用bean验证1.1,我想验证一个bean(在类级别)并为多个字段添加反馈给用户。

我希望实现的高级别(省略了可读性代码)

@RequestCheck
public class Request {
    private String param1;
    private String param2;
    private String param3;
}

public class RequestCheckValidator implements ConstraintValidator<RequestCheck, Request> {
    //...
    public boolean isValid(final Request request, final ConstraintValidatorContext context) {
        if (request.param1 != null || request.param2 != null || request.param3 != null)
            context.disableDefaultConstraintViolation();
            final ConstraintViolationBuilder violationBuilder = context.buildConstraintViolationWithTemplate("There are missing parameters.");
            if (request.param1 == null) {
                valid = false;
                violationBuilder.addPropertyNode("param1");
            }
            if (request.param2() == null) {
                valid = false;
                violationBuilder.addPropertyNode("param2");
            }
            if (request.param3() == null) {
                valid = false;
                violationBuilder.addPropertyNode("param3");
            }
            violationBuilder.addConstraintViolation();
            //return ...
        }
    }

问题是添加第二个addProperyNode("...")会抛出一个nullpointer。 当验证适用于类时,如何正确地向反馈添加额外参数?

- 编辑 - 要清除:我需要在类级别使用此注释,因为验证取决于字段的组合。他们需要所有人都在场,或者他们都不在场。

提前致谢!

1 个答案:

答案 0 :(得分:0)

好的,这实际上很简单,你只需要为每次违规创建一个构建器:

context.buildConstraintViolationWithTemplate("if a parameter is supplied, please provide all parametes. param1 is Missing")
               .addPropertyNode("param1")
               .addConstraintViolation();