gpt4 book ai didi

java - 如何以编程方式配置 Bean 验证?

转载 作者:行者123 更新时间:2023-12-02 12:40:12 25 4
gpt4 key购买 nike

我想使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com