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

。_饼干妹妹 提交于 2019-12-03 07:46:54
Sabir Khan

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!