Annotations from javax.validation.constraints not working

后端 未结 15 1279
广开言路
广开言路 2020-11-28 06:23

What configuration is needed to use annotations from javax.validation.constraints like @Size, @NotNull, etc.? Here\'s my code:

相关标签:
15条回答
  • 2020-11-28 06:49

    After the Version 2.3.0 the "spring-boot-strarter-test" (that included the NotNull/NotBlank/etc) is now "sprnig boot-strarter-validation"

    Just change it from ....-test to ...-validation and it should work.

    If not downgrading the version that you are using to 2.1.3 also will solve it.

    0 讨论(0)
  • 2020-11-28 06:50

    So @Valid at service interface would work for only that object. If you have any more validations within the hierarchy of ServiceRequest object then you might to have explicitly trigger validations. So this is how I have done it:

    public class ServiceRequestValidator {
    
          private static Validator validator;
    
          @PostConstruct
          public void init(){
             validator = Validation.buildDefaultValidatorFactory().getValidator();
          }
    
          public static <T> void validate(T t){
            Set<ConstraintViolation<T>> errors = validator.validate(t);
            if(CollectionUtils.isNotEmpty(errors)){
              throw new ConstraintViolationException(errors);
            }
         }
    
    }
    

    You need to have following annotations at the object level if you want to trigger validation for that object.

    @Valid
    @NotNull
    
    0 讨论(0)
  • 2020-11-28 06:50

    Great answer from atrain, but maybe better solution to catch exceptions is to utilize own HandlerExceptionResolver and catch

    @Override
    public ModelAndView resolveException(
        HttpServletRequest aReq, 
        HttpServletResponse aRes,
        Object aHandler, 
        Exception anExc
    ){
        // ....
        if(anExc instanceof MethodArgumentNotValidException) // do your handle     error here
    }
    

    Then you're able to keep your handler as clean as possible. You don't need BindingResult, Model and SomeFormBean in myHandlerMethod anymore.

    0 讨论(0)
提交回复
热议问题