I used to validate my beans inside my spring @RestController
like:
@PostMapping("/documents")
@ResponseStatus(HttpStatus.CREATED)
fun create(@Valid @RequestBody document: DocumentCreate) {
return documentService.create(document)
}
Even it seems stupid, I would like now to validate my bean depending on a DocumentCreate
boolean property like:
@PostMapping("/documents")
@ResponseStatus(HttpStatus.CREATED)
fun create(@RequestBody document: DocumentCreate) {
return when {
document.needValidation -> documentService.createWithValidation(document),
else -> documentService.createWithoutValidation(document)
}
}
I tried to move the @Valid
annotation to the document @Service
class but it does not trigger the validation. How can I achieve this? Is it possible?
The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. We'll learn more about how to use it in the section about validating path variables and request parameters.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
Annotation Type ValidMarks a property, method parameter or method return type for validation cascading. Constraints defined on the object and its properties are be validated when the property, method parameter or method return type is validated. This behavior is applied recursively.
for anyone who is wondering how to do it using annotation. Annotate your service class with spring's @Validated. Once done, it will fire the validation of the input bean in your service class method that is decorated with @Valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With