Usage of @Valid vs @Validated in Spring

巧了我就是萌 提交于 2021-01-29 02:28:52

问题


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.


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!