spring validation in composition

Viewed 213

I have the following data classes:

data class User (
    @field:NotEmpty
    val firstName: String?
    @field:NotEmpty
    val lastName: String?
)

data class Expert (
    @field:NotEmpty
    val name: String?
    @field:NotNull
    val contact: User?
)

And I would like to use my rest API endpoint to create an expert with spring validation:

@RestController
@RequestMapping("/api/experts")
class ExpertController(private val expertService: ExpertService) {

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    fun create(@Valid @RequestBody dto: Expert) = expertService.create(dto)

}

Validation on name and contact fields works fine. But validation on firstName and lastName fields (User class) doesn't work. Is it a normal behaviour? I can't use validation on composition? Why? Or am I missing something?

1 Answers

In order for the User to be validated if it is contained within an Expert, you will need to add the @Valid annotation to it, so Spring's Validator knows to keep checking, otherwise it will stop.

Try this (untested):

data class Expert (
    @field:NotEmpty
    val name: String?

    @field:NotNull
    @field:Valid
    val contact: User?
)
Related