2

I have a model with a field annotated with @NotNull

public class Employee {
    @NotNull
    private String name;
    //other fields and getters/setters
}

But I don't have controllers. All I want to do is invoke validation on Employee model either when this method is invoked (this method is in a class that's a Spring component), or manual validation.

When using controllers, I could have annotation handler method with @Valid Employee emp followed by BindingResults. But I don't have controllers.

Or in some scenarios, I could have implemented Validator interface, And then used a combination of BeanPropertyBindingResult and ValidationUtils.invokeValidator. But again, in this case, That @NotNull on model Employee would not be invoked unless I add validation for it in Validator implementation.

Is there another way?

Faraz
  • 6,025
  • 5
  • 31
  • 88

1 Answers1

0

Found the solution posted by this guy. Use this in the method:

javax.validation.Validator javaxValidator = javax.validation.Validation.buildDefaultValidatorFactory().getValidator();

org.springframework.validation.beanvalidation.SpringValidatorAdapter validator = new org.springframework.validation.beanvalidation.SpringValidatorAdapter(javaxValidator);

org.springframework.validation.Errors errors = new org.springframework.validation.BeanPropertyBindingResult.BeanPropertyBindingResult(objectThatNeedsToBeValidated, objectThatNeedsToBeValidated.getClass().getName());
validator.validate(objectThatNeedsToBeValidated, errors);

Edit: This is better than the above solution.

Faraz
  • 6,025
  • 5
  • 31
  • 88