Skip to content
Advertisement

Does anyone know why @Valid fails with javax.validation and works with spring starter validation

I have the following controller:

JavaScript

which uses this dependency, among others:

JavaScript

the LibraryEvent DTO looks like this:

JavaScript

And the book inside that library event, is the following:

JavaScript

I also have this test which uses MockMvc to send a mocked request to the controller in order to test that one:

JavaScript

Everything is fine so far, the problem is that in my build.gradle I was using javax.validation dependency, and when I ran the test with that dependency, the @Valid annotation did not work because it returned HttpStatus.OK (200) instead of Bad request (400), that is supposed to be, because the id and author of the book were passed as null. This is how my dependencies section of my gradle file was set with javax:

JavaScript

I solved the problem by replacing the javax dependency with the spring boot starter validation one, once I ran the test again after that change, it passed and the @Valid in the controller worked because the test returned 4XX HTTP status. My gradle now looks like this:

JavaScript

But this is pretty weird, because spring validation is supposed to use the same validations that javax use or at least the @Valid should behave the same way. So my question is, can anyone explain to me what is the difference between javax validation and spring validation, and why that has failed with javax, and not with spring validation?

Thank you in advance!

Advertisement

Answer

The Spring documentation at https://docs.spring.io/spring-framework/docs/5.3.9/reference/html/core.html#validation-beanvalidation-spring gives the following example for bootstrapping a Bean Validation Provider:

JavaScript

And it goes on with remarking:

A Bean Validation provider, such as the Hibernate Validator, is expected to be present in the classpath and is automatically detected.

The spring-boot-starter-validation dependency seems to do just these two things.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement