JSR - 349 bean validation for Spring @RestController with Spring Boot

后端 未结 2 1867
醉梦人生
醉梦人生 2021-02-09 15:33

I am using Spring Boot 1.5.2.RELEASE and not able to incorporate JSR - 349 ( bean validation 1.1 ) for @RequestParam & @PathVariable at method itse

相关标签:
2条回答
  • 2021-02-09 16:09

    I had asked the question after more than two days of unsuccessful hit & trial. Lots of confusing answers are out there because of confusions around Spring Validations and JSR validations, how Spring invokes JSR validators, changes in JSR standards & types of validations supported.

    Finally, this article helped a lot.

    I solved problem in two steps,

    1.Added following beans to my Configuration - without these beans , nothing works.

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor();
        mvProcessor.setValidator(validator());
        return mvProcessor;
    }           
    
    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setProviderClass(HibernateValidator.class);
        validator.afterPropertiesSet();
        return validator;
    }
    

    2.Placed Spring's @Validated annotation on my controller like below,

    @RestController
    @RequestMapping("/...")
    @Validated
    public class MyRestController {
    }
    

    Validated is - org.springframework.validation.annotation.Validated

    This set up doesn't affected @Valid annotations for @RequestBody validations in same controller and those continued to work as those were.

    So now, I can trigger validations like below for methods in MyRestController class,

    @RequestMapping(method = RequestMethod.GET, value = "/testValidated" , consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean<String> testValidated(
            @Email(message="email RequestParam is not a valid email address") 
            @NotEmpty(message="email RequestParam is empty") 
            @RequestParam("email") String email) {
        ResponseBean<String> response = new ResponseBean<>();
        ....
        return response; 
    }
    

    I had to add another handler in exception handler for exception - ConstraintViolationException though since @Validated throws this exception while @Valid throws MethodArgumentNotValidException

    0 讨论(0)
  • 2021-02-09 16:34

    Spring @Validated @Controller did not mapped when adding @Validated. Removal of any inheritance from controller itself did help. Otherwise Sabir Khan's answer worked and did help.

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