Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Valid @CustomValidator inside a spring @Service

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?

like image 935
louis amoros Avatar asked Sep 11 '18 15:09

louis amoros


People also ask

What does @valid do in Spring?

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.

What is the use of @valid annotation in Spring boot?

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.

What is @valid annotation in Java?

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.


1 Answers

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.

like image 121
Vishal Avatar answered Sep 19 '22 14:09

Vishal