Artur Skrzydło
Artur Skrzydło

Reputation: 1155

Getting ConstraintViolationException when trying to use BindingResult in Spring Controller

I have and endpoint, where I validate received json document which contains collections of objects. I would like to only log these objects which don't pass a validation, when others i would like to store in db. Controller should return 200 OK in that situation. I was trying to use BindingResult object for this purpose. Unfortunately i always get a ConstraintViolationException. It seems that it validates it before it enter the method and throw exception. How can I force it to use BindingResult object ?

@RestController
@Validated
@RequestMapping(path = "/test")
class TestController {

    @PostMapping(consumes = APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> addObjects(@RequestBody @Valid List<Document> objects, BindingResult bindingResult) {

        if(bindingResult.hasErrors()){

        }            
        return new ResponseEntity<Void>(HttpStatus.OK);
    }

}

I'm using Spring Boot 1.5.9.RELEASE with Java 8

Upvotes: 0

Views: 1676

Answers (2)

Artur Skrzydło
Artur Skrzydło

Reputation: 1155

I've managed to solve it finally. Problem is with @Validated annotation on controller class. With this annotation spring do a validation on request and throw ConstraintViolationException. Without that, validation is triggered later and it results are stored in BindingResult object as expected

Upvotes: 2

regenti88
regenti88

Reputation: 83

Could You please add the model classes with its annotations? Remember that if You have any fields in Document class which are Your custom defined classes and You want it to be validated also then You have to decorate these fields with @Valid annotation too.

Upvotes: 0

Related Questions