【发布时间】:2019-02-25 22:06:13
【问题描述】:
在我用 Kotlin 构建的 Spring 应用程序中,我想在一个看起来像这样的数据类上使用 bean 验证。
data class CustomerDto(
@field: NotBlank
val firstName: String,
@field: NotBlank
val lastName: String)
在向客户端点发送一个空名字的帖子时,我想获得约束验证,但由于字段不允许空值,我没有得到验证,而是得到以下错误。
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Instantiation of [simple type, class pkg.CustomerDto] value failed for JSON property firstName due to missing (therefore NULL) value for creator parameter firstName which is a non-nullable type; nested exception is com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class pkg.CustomerDto] value failed for JSON property firstName due to missing (therefore NULL) value for creator parameter firstName which is a non-nullable type\n at [Source: (PushbackInputStream); line: 19, column: 1] (through reference chain: pkg.CustomerDto[\"firstName\"])",
"path": "/shop/5/customer"
是否有任何其他选项可以将 dto 字段标记为非可选并且仍然违反约束?当我将它们标记为可选时,我必须使用 !!将代码中的不可空字段映射到我的实体时。
谢谢。
【问题讨论】:
-
好问题,这里的沉默可能支持了我的印象。 Imo 没有办法,因为成功构建对象是字段验证的先决条件。不过,我很想阅读 Kotlin 冠军的观点。我已经想到了一个与 Spring 相关的解决方案,但我猜你想用 Kotlin 方式解决它?
-
不,我没有一个好的解决方案,除了让所有东西都是可选的或使用 !!当映射到我的实体以依赖我的模型中的空安全性时。我会对您想到的 Spring 解决方案感兴趣。
-
在做了一点搜索之后,我想,这可能比我最初想象的要难一些,但是,可能的。问题是,如果这些方法证明你需要付出的努力是合理的。首先是使用 Spring AOP,第二个 HandlerInterceptors 让您在 Jackson 将请求负载反序列化到您的 CustomerDTO 之前访问和修改请求。这绝对不是一个简单的解决方案,看看这个问题:stackoverflow.com/questions/50932518/…
标签: java spring kotlin bean-validation