2

Thanks to this question, I think I understand how validation is working.

As for JPA, here we have a specification called JSR-303 explaining how Bean Validation should work and then we are using implementations like the commonly used Hibernate Validator or Apache BVal also.

I am struggling about using @Validin some part of my code. I am not using @Validated because I do not need group validation.

You can find an example of a demo project here

In PropertyExample class, you can see I marked my class for bean validation to happen.

When using @Validated, everything work as expected since I am violating a constraint in my application.yml file. When using @Valid over @Validated, it seems nothing happens. I do not understand why.

I saw too that those annotations could be used on ElementType.PARAMETER but when I am using using them during constructor initialisation, validation doesn't seem to trigger either.

Explanations on how to used those annotations (especially the @Valid) would be greatly appreciated.

MadJlzz
  • 767
  • 2
  • 13
  • 35
  • You need `@Validated` to be placed on the type (class) per [Spring Boot documentation] (https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-validation) in order to have validation to be triggered on its methods that are annotated with, say, `@Valid` or `@Null`. I still haven't figured out why, as `@Validated` only adds *group validation* to the mix. Perhaps this post explains a bit further: https://stackoverflow.com/a/19426570/2187022 – NuCradle Jun 30 '19 at 03:52

1 Answers1

2

It works when using Validated and doesn't when using Valid simply because Spring Boot requires properties classes to be annotated with Validated if you want them to be validated. See the documentation:

Spring Boot attempts to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation

[...]

You can also trigger validation by annotating the @Bean method that creates the configuration properties with @Validated.

Note that they can't possibly allow the use of Valid on properties classes, since the Valid annotation isn't applicable to classes.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Ok that makes sense but when are we using `@Valid` then ? Is there any use case ? – MadJlzz Jun 29 '19 at 11:22
  • The tell the validator that a field must be validated, too. Or to validate MVC method parameters. https://docs.oracle.com/javaee/7/api/javax/validation/Valid.html – JB Nizet Jun 29 '19 at 11:29
  • Ok so it behaves like a marker then. Much more clearer now thanks. – MadJlzz Jun 29 '19 at 11:40
  • Note that they can't possibly allow the use of Valid on properties classes, since the Valid annotation isn't applicable to classes. – JB Nizet Jun 29 '19 at 11:48