gpt4 book ai didi

java - Kotlin Spring bean 验证可空性

转载 作者:IT老高 更新时间:2023-10-28 13:40:41 26 4
gpt4 key购买 nike

在我用 Kotlin 构建的 Spring 应用程序中,我想在一个看起来像这样的数据类上使用 bean 验证。

data class CustomerDto(
@field: NotBlank
val firstName: String,

@field: NotBlank
val lastName: String)

在向客户端点发送 firstName 为空的帖子时,我想获得约束验证,但由于字段不允许空值,我没有获得验证,而是收到以下错误。

"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 字段标记为非可选并且仍然违反约束?当我将它们标记为可选时,我必须使用 !!将代码中的不可为空字段映射到我的实体时。

谢谢。

最佳答案

我相信你走错路了。

Kotlin 的空安全运算符的确切目的是强制您在代码中明确表达可空性行为,以大幅减少 NPE,或者至少确保您自己故意造成它们 :)。在您(或任何类似 MVC 的访问模式)的情况下,您将面临以下情况

  • 作为 DTO 有效负载的一部分,字段可能为空
  • 如果字段为空,框架验证应取消 DTO 的资格。
  • 如果框架验证成功,则隐式假定 DTO 字段不为空

虽然从逻辑流的角度来看是有道理的,但它实际上是可能导致 NPE 的违规行为,因为模型/契约(Contract)中没有任何内容可以保证这些字段不会为空

不过,在 java 中,您只是使用 getter 做出了最后的假设(无论如何,您一直在使用 getter,它是 java,对吧?)。

好吧 - 如果你需要的话,在 kotlin 中也没有什么不同:

data class CustomerDto(@field:NotNull 
@JsonProperty("firstName") private val _firstName: String? = null,
@field:NotNull
@JsonProperty("lastName") private val _lastName: String? = null) {
val firstName get() = _firstName!!
val lastName get() = _lastName!!
}

(此示例假设您使用 jackson 进行 JSON 反序列化)

虽然仍然使用 !! 运算符手动强制不可为空(这是您想要避免的),但您现在正在从代码库的其余部分中抽象出该方面,获得 java-getter喜欢的行为

关于java - Kotlin Spring bean 验证可空性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52444699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com