我有以下数据类:
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?
)
我想使用我的 rest 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)
}
验证在
name
和 contact
字段工作正常。但在 firstName
上进行验证和 lastName
字段( User
类)不起作用。这是正常行为吗?我不能对构图使用验证?为什么?或者我错过了什么?
最佳答案
为了User
如果它包含在 Expert
中,则进行验证,您需要添加 @Valid
给它注释,所以 Spring 的 Validator 知道要继续检查,否则它会停止。
试试这个(未经测试):
data class Expert (
@field:NotEmpty
val name: String?
@field:NotNull
@field:Valid
val contact: User?
)
关于组合中的 Spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52151903/