繁体   English   中英

Kotlin Spring bean 验证可空性

[英]Kotlin Spring bean validation nullability

在我使用 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 的 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!!
    }

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

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

我认为更好的解决方案是在属性中使用 Kotlin 的默认值:

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

@field: NotBlank
val lastName: String="")

名字和姓氏属性将始终具有一个值(来自 json 或默认值 ="")。 该解决方案并不完美,但它的工作方式符合预期。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM