问题描述
我正在尝试使用 javax.validation 验证控制器外部的类并生成 MethodArgumentNotValidException 类型的异常。我查看了以下论坛,但到目前为止它们都没有帮助:
Manually call Spring Annotation Validation Outside of Spring MVC
Using Spring Validator outside of the context of Spring MVC
我想要实现的是以下
public class Classtest {
@NotEmpty
private String property1;
@NotNull
private String property2;
}
在我的验证类中执行以下操作(不是控制器),传播生成的异常(NotNull、NotEmpty、NotBlank、Pattern 等)
void validationClass(boolean value) {
Classtest classtest = new Classtest();
if (value) {
//perform class validation
errors = validation(classtest);
throw new MethodArgumentNotValidException(errors);
} else {
//OK
}
}
感谢您的帮助
解决方法
如果我理解正确,您想进行一些自定义验证吗?
public class CustomValidator {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
void validate(Object object) {
Set<ConstraintViolation<?>> violations = validator.validate(object);
if (validations.size() > 0) {
String errorMessage =
violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.join(",");
throw new MethodArgumentNotValidException(errorMessage);
}
}
}