Manually call Spring Annotation Validation

后端 未结 6 1705
太阳男子
太阳男子 2020-11-29 02:42

I\'m doing a lot of our validation with Hibernate and Spring Annotations like so:

public class Account {
    @NotEmpty(groups = {Step1.class, Step2.class})
          


        
6条回答
  •  囚心锁ツ
    2020-11-29 03:36

    This link gives pretty good examples of using validations in Spring apps. https://reflectoring.io/bean-validation-with-spring-boot/

    I have found an example to run the validation programmitically in this article.

    class MyValidatingService {
    
      void validatePerson(Person person) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set> violations = validator.validate(person);
        if (!violations.isEmpty()) {
          throw new ConstraintViolationException(violations);
        }
      } 
    }
    

    It throws 500 status, so it is recommended to handle it with custom exception handler.

    @ControllerAdvice(annotations = RestController.class)
    public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
        @ExceptionHandler(ConstraintViolationException.class)
        public ResponseEntity constraintViolationException(HttpServletResponse response, Exception ex) throws IOException {
            CustomErrorResponse errorResponse = new CustomErrorResponse();
            errorResponse.setTimestamp(LocalDateTime.now());
            errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());
            errorResponse.setError(HttpStatus.BAD_REQUEST.getReasonPhrase());
            errorResponse.setMessage(ex.getMessage());
            return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
        }
    }
    

    Second example is from https://www.mkyong.com/spring-boot/spring-rest-error-handling-example/

    Update: Using validation is persistence layer is not recommended: https://twitter.com/odrotbohm/status/1055015506326052865

提交回复
热议问题