【问题标题】:Spring Validation of JSON - Why do I need to add `@field`JSON的Spring验证 - 为什么我需要添加`@field`
【发布时间】:2019-08-02 08:06:40
【问题描述】:

我终于在 Spring 验证方面取得了一些进展(在来自 RabbitMQ 的 JSON 对象上)。

但是有几件事我不明白:

  • 在文档中,它声明我可以只使用注释@NotBlank,然后在我的方法中使用注释@Valid。但是我发现这并没有做任何事情。因此,我改为使用@field:NotBlank,它与以下内容一起工作 - 为什么这个@field 能做到这一点?
    @JsonIgnoreProperties(ignoreUnknown = true)
    data class MyModel (
            @field:NotBlank(message = "ID cannot be blank")
            val id : String = "",
            @field:NotBlank(message = "s3FilePath cannot be blank")
            val s3FilePath : String = ""
    )

那么使用这个模型的函数:

    @Service
    class Listener {
        @RabbitListener(queues = ["\${newsong.queue}"])
        fun received(data: MyModel) {

            val factory = Validation.buildDefaultValidatorFactory()
            val validator = factory.validator
            val validate = validator.validate(data)
            // Then this `validate` will return an array of validation errors
            println(validate)
        }

    }
  • 如果我错了,请纠正我,但是我假设只使用 @Valid 而这一点 fun received(@Valid data: MyModel) 它只会抛出一些异常让我捕捉 - 基于我的代码的任何想法为什么会这样?

任何建议/帮助将不胜感激。

谢谢。

这里是导入:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import javax.validation.*
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.rabbit.annotation.RabbitListener
import javax.validation.constraints.NotBlank

【问题讨论】:

  • 你能粘贴你的导入吗?
  • 附在问题中

标签: spring spring-boot kotlin rabbitmq


【解决方案1】:

引用 Kotlin 的 documentation 进行注释:

当您注释属性或主要构造函数参数时,会从相应的 Kotlin 元素生成多个 Java 元素,因此在生成的 Java 字节码中有多个可能的注释位置。要指定应如何准确生成注释,请使用以下语法:

class Example(@field:Ann val foo,    // annotate Java field
              @get:Ann val bar,      // annotate Java getter
              @param:Ann val quux)   // annotate Java constructor parameter

因此,除非在 Kotlin 类构造函数中明确提及您要注释的内容(字段、getter 或其他内容),否则它不会自动知道您要将注释放在哪里。

【讨论】:

    猜你喜欢
    • 2020-10-11
    • 2011-01-02
    • 2023-03-22
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2020-11-16
    • 1970-01-01
    相关资源
    最近更新 更多