2

Note: I read almost all stack post that i get when i search @valid vs @validated and could not find answer so i am posting this.

I am so confused what @Validated is doing here. If inputParms is not valid, it is throwing javax.validation.ConstraintViolationException and not even going inside code. But if I replace @Validated with @Valid No exception thrown and bindingResult.hasErrors() is catching it.

@RestController
@Validated // what is this doing ??
public class MyRestController{
    @PostMapping(value="/my-data",produces= {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<?> doSomething(@Valid @RequestBody MyInputParam inputParms,BindingResult bindingResult){
        if(bindingResult.hasErrors()) {
            //do something here
        }
    }
}

So if i use @Validated, BindingResult is not useful at all ? Or even simply how @Validated is different from @Valid

user9735824
  • 1,196
  • 5
  • 19
  • 36

1 Answers1

0

See Difference between @Valid and @Validated in Spring.

The problem in your particular case is that @Validated is mixed with @Valid. Options to fix this:

  • remove the @Validated declared on the class and use either @Validated or @Valid for the parameter
  • use either @Valid or @Validated in both places (class and parameter)
@RestController
public class MyRestController {

    @PostMapping(value = "/my-data", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<?> doSomething(@Validated @RequestBody MyInputParam inputParms, 
                                         BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            //do something here
        }
    }

}
Andrei Damian-Fekete
  • 1,820
  • 21
  • 27
  • The link that you mentioned is already on my question as i read that. The solution you are saying works but my question is if i use validated on class level and valid on method, what is throrwing `javax.validation.ConstraintViolationException`. I am sure i am missing somethig here. – user9735824 Jul 17 '19 at 15:05