问题
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 @Valid
in 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.
回答1:
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.
来源:https://stackoverflow.com/questions/56817075/usage-of-valid-vs-validated-in-spring