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 here
MsgValidator msgValidator = new MsgValidator();
Boolean isValid = msgValidator.validateMsg(internalMsg);
// some other processings
return 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 working Please let me know how to achieve this