我想使用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 类上运行...所以问题是我可以以及如何配置不每次都在每个变量上运行?
最佳答案
您应该使用Validator::validateProperty
检查特定属性。您还可以将它们分组并通过 Validator::validate
查看。 (请参阅 here 教程)如果有多个属性。
关于java - 如何以编程方式配置 Bean 验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44967217/