在控制器 springboot 之外使用 javax.validation

我正在尝试使用 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
    }
}

感谢您的帮助

fengziyun 回答:在控制器 springboot 之外使用 javax.validation

如果我理解正确,您想进行一些自定义验证吗?

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);
  }
 }
}
本文链接:https://www.f2er.com/1088489.html

大家都在问