春季作文验证

时间:2018-09-03 14:40:48

标签: spring validation kotlin

我有以下数据类:

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?
)

我想使用我的其余API端点来创建具有spring验证的专家:

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

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

}
namecontact字段上进行验证有效。但是无法对firstNamelastName字段(User类)进行验证。这是正常行为吗?我不能对组合使用验证吗?为什么?还是我错过了什么?

1 个答案:

答案 0 :(得分:2)

要验证User是否包含在Expert中,您需要向其添加@Valid批注,因此Spring的Validator会继续检查,否则它将停止。

尝试一下(未试用):

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

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