0

I'm trying to validate a class outside of the controller using javax.validation and generating an exception of type MethodArgumentNotValidException. I reviewed the following forums, but not so far they have not been helpful:
Manually call Spring Annotation Validation Outside of Spring MVC
Using Spring Validator outside of the context of Spring MVC

What I want to achieve is the following

public class ClassTest {
    @NotEmpty
    private String property1;

    @NotNull
    private String property2;
}

In my validations class do the following (is not a controller), propagating the generated exception (NotNull, NotEmpty, NotBlank, Pattern, others)

void validationClass(boolean value) {
    ClassTest classTest = new ClassTest();

    if (value) {
        //perform class validation
        errors = validation(classTest);
        throw new MethodArgumentNotValidException(errors);
    } else {
        //OK
    }
}

Thanks for your help

1 Answers1

1

if I understand you right, you want to do some custom 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);
  }
 }
}
Yegor Saliev
  • 105
  • 1
  • 11
  • In effect, it is something custom, however, it does not require the message, but the error generated (NotNull, NotEmpty, NotBlank) – Carlos Sanchez Jan 18 '21 at 01:05