【问题标题】:@Valid annotation is not validating the list of child objects - Spring Boot + Kotlin@Valid 注释不验证子对象列表 - Spring Boot + Kotlin
【发布时间】:2021-06-23 18:44:21
【问题描述】:

我有一个与这个主题 @Valid annotation is not validating the list of child objects 非常相似的问题,但我尝试使用 Kotlin 来实现。

@Valid 注释不适用于WordDto。仅评估类 MessageDto

@SpringBootApplication
class ValidationsApplication

fun main(args: Array<String>) {
    runApplication<ValidationsApplication>(*args)
}

data class WordDto(
    @field:Max(5)
    val word: String
)

data class MessageDto(
    @Valid
    @field:NotEmpty
    val words: List<WordDto>
)

@RestController
class Controller {
    @PostMapping("/hello")
    fun hello(@Valid @RequestBody messageDto: MessageDto) {
        messageDto.words.map(System.out::println)
    }
}

我也尝试过这种方法:

val words: List<@Valid WordDto>

还写了这个应该通过的测试:

@Test
    fun `should validate child objects`() {
        val dto = MessageDto(
            words = listOf(
                WordDto("Long Word that should fail")
            )
        )

        val violations = validator.validate(dto)

        assertThat(violations).isNotEmpty()
    }

依赖关系:

    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-validation")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")

对可能缺少什么有什么想法吗?

项目可以在Github找到

【问题讨论】:

  • @Valid => MessageDto 类中的@field:Valid
  • @NikolaiShevchenko 非常感谢,这就是缺少的!

标签: spring-boot kotlin


【解决方案1】:

按照@NikolaiShevchenko 的回答,这就是解决方案。

data class MessageDto(
    @field:Valid
    @field:NotEmpty
    val words: List<WordDto>
)

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 2022-01-01
    • 2018-07-04
    • 2020-10-30
    • 2021-09-24
    • 1970-01-01
    • 2018-07-14
    • 2017-11-28
    • 2019-12-04
    相关资源
    最近更新 更多