Kotlin Spring bean验证可空性

jge*_*rts 8 java spring bean-validation kotlin

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

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

    @field: NotBlank
    val lastName: String)
Run Code Online (Sandbox Code Playgroud)

在将具有空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"
Run Code Online (Sandbox Code Playgroud)

是否有任何其他选项可以将dto字段标记为不可选且仍然可以获得约束违规?当我将它们标记为可选时,我必须使用!! 在将它们映射到我的实体时,代码中的不可空字段.

谢谢.

She*_*gon 8

我相信你的做法是错误的。

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

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

虽然它在逻辑流方面是有意义的,但实际上是一种可能导致 NPE 的违规行为,因为模型/合约中没有任何内容保证这些字段不会为空

不过,在 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!!
    }
Run Code Online (Sandbox Code Playgroud)

(此示例假设您用于jacksonJSON 反/序列化)

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