如何以编程方式配置 bean 验证?

How to configure bean validation programatically?

我想使用 bean 验证的代码:

@Inject
private ValidatorFactory validatorFactory;
....

public Response create(@Context HttpServletRequest request) {
        ...
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}


public Response update(@Context HttpServletRequest request) {
        Set<ConstraintViolation<UserDTO>> validate = validatorFactory.getValidator().validate(userDTO);
        validate.forEach(error-> System.err.println(error.getMessage()));
        if(validate.size() > 0){
            throw new ValidationException("userDTO is not valid!");
        }
        ...
}

用户DTO:

public class UserDTO {
    private Integer id;
    private String userName;
    @NotNull(message = "is missing")
    private String locked;
    @Email(message = "email is not valid")
    private String email;
    @NotNull(message = "countryCode is missing")
    private String countryCode;
    ...getters-setters more variables...
}

所以我有一个 post Http 方法,我想在其中创建一个用户...如果缺少国家代码或已锁定,或者如果电子邮件无效,则 bean 验证工作正常...但是当我想只需更新例如电子邮件,验证在整个 dto class 上也是 运行...所以问题是我可以以及我如何配置不对每个变量每次都 运行?

如果有多个 属性.

,您应该使用 Validator::validateProperty to check specifc properties. You can also group them and check it via Validator::validate (see here 作为教程)