@Valid @CustomValidator inside a spring @Service

Viewed 2466

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?

2 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.

I found a solution by instantiating a validator bean:

import javax.validation.Validator
...
@Autowired
lateinit var validator: Validator

and I use it in my create function:

@PostMapping("/documents")
@ResponseStatus(HttpStatus.CREATED)
fun create(@RequestBody document: DocumentCreate) {
    return when {
        document.needValidation -> {
            val errors = validator.validate(document)
            if (errors.isNotEmpty()) {
                throw ConstraintViolationException(errors)
            }
            documentService.create(document)
        }
        else -> documentService.create(document)
    }
}

I did not find a way to do it with annotations in the service layer.

Related