I am validating java beans using spring-boot-starter-validation.

Validation on the controller is working fine,

I want to know whether can we validate the normal methods of a class using @Valid annotation? I have tried it but not working.

My working solution on the controller

@PostMapping("/testMessage")ResponseEntity<String> testMethod(@Valid @RequestBody InternalMsg internalMsg) {return ResponseEntity.ok("Valid Message");}

I want to move the validation to a class method so that when I hit the RestAPI, the validation errors are captured in a new method.

Let's say the method is validateMsg of class MsgValidator and I am calling this method inside controller code

@PostMapping("/testMessage")ResponseEntity<String> testMethod(@RequestBody InternalMsg internalMsg) { // No @Valid hereMsgValidator msgValidator = new MsgValidator();Boolean isValid = msgValidator.validateMsg(internalMsg);// some other processingsreturn ResponseEntity.ok("Valid Message");}public class MsgValidator{public boolean validateMsg(@Valid InteropMsg interopMsg){return true;}@ResponseStatus(HttpStatus.OK)@ExceptionHandler(MethodArgumentNotValidException.class)public ResponseEntity<Ack> handleValidationExceptions(MethodArgumentNotValidException ex) {StringBuilder errorMessages = new StringBuilder("");ex.getBindingResult().getAllErrors().forEach((error) -> {errorMessages.append(error.getDefaultMessage()).append(";");});log.error("Validation errors : "+errorMessages.toString());return ResponseEntity.ok().body(ack);}}public class InternalMsg implements Serializable {@NotNull(message = "Msg Num is a required field")private String msgNumber;@NotNull(message = "Activity Name is a required field")private String activityName;}

This is not workingPlease let me know how to achieve this

1

Best Answer


Below is an example of how you could use the ValidatorFactory to get a Validator to do the validation rather than using the @Valid annotation.

 InternalMsg internalMsg = new InternalMsg();ValidatorFactory factory = Validation.buildDefaultValidatorFactory();Validator validator = factory.getValidator();Set<ConstraintViolation<InternalMsg>> validate = validator.validate(internalMsg);

See here for more details -> https://www.baeldung.com/javax-validation

The below is just a snippet and not necessarily the recommended way of using the ValidationFactory