Spring Boot: How to validate all parameters in a RestController

Viewed 66

Say I have a @RestController with 10 methods, each of which takes one or more parameters. How can I tell Spring to validate each and every one of those parameters without annotating all of them with @Valid?

I already tried annotating the whole class with @Validated but to no effect. Maybe I have missed a necessary configuration?

The controller:

import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController

@Validated
@RestController
class EntityController {

    @PutMapping("/{id}")
    fun update(@PathVariable id: UUID, @RequestBody entityDto: EntityDto) {
        // update the entity
    }

    // more methods
}

and the DTO:

import javax.validation.constraints.NotBlank

data class EntityDto(
    @field:NotBlank
    private val name: String
)

It works perfectly well if I add @Valid to the @RequestBody annotation at method level. Then requests like PUT /123 { "name": " " } are rejected because of the blank name field.

Any clues as to how I get my controller to validate every object regardless of @Valid annotation?

1 Answers
Related