使用Hibernate Validator自定义类级别验证,而无需使用注释。
示例代码:
public class User {
private String name;
@Valid
private Address address;
// getters and setters
}
public class Address {
private String street1;
private String street2;
private String city;
private String state;
private String zipCode;
// getters and setters
}
public class UserValidator implements ConstraintValidator {
@Override
public boolean isValid(User user, ConstraintValidatorContext context) {
// check if user name is not empty
if (StringUtils.isBlank(user.getName())) {
context.buildConstraintViolationWithTemplate("User name cannot be blank")
.addPropertyNode("name")
.addConstraintViolation();
return false;
}
// check if user address is valid
if (user.getAddress() != null) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set> constraintViolations = validator.validate(user.getAddress());
if (!constraintViolations.isEmpty()) {
for (ConstraintViolation violation : constraintViolations) {
context.buildConstraintViolationWithTemplate(violation.getMessage())
.addPropertyNode("address." + violation.getPropertyPath().toString())
.addConstraintViolation();
}
return false;
}
}
return true;
}
}
该代码使用ConstraintValidator
接口自定义了isValid
方法,实现了类级别验证。在示例中,使用了StringUtils
和Validation
类和它们的方法。isValid
方法检查了用户姓名是否为空值,还验证了用户地址是否有效。如果验证失败,则在ConstraintValidatorContext
对象中添加验证约束违规。在User
类中,使用了@ValidUser
注释来指定类级别验证。
注意:在META-INF/validation.xml
文件中添加以下内容启用类级别验证。
com.example.myapp
com.example.myapp.User
com.example.myapp.UserValidator
下一篇:不使用主文件中的变量来调用外部类