Spring Webflux bean验证不起作用 [英] Spring webflux bean validation not working

查看:358
本文介绍了Spring Webflux bean验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Webflux中使用bean验证.这是我到目前为止的内容:

I am trying to use bean validation in Webflux. This is what I have so far:

@PostMapping("contact")
fun create(@RequestBody @Valid contact: Mono<Contact>) : Mono<Contact> {
    return contact.flatMap { contactRepository.save(it) }
            .doOnError{ Error("test") }
}

验证不起作用...我希望显示Error("test") ...

The The validation doesn't work... I would expect that the Error("test") would be shown...

有人有可行的示例(Java或Kotlin)吗?

Does someone has a working example(Java or Kotlin)?

更新

这里是一个存储库,因此可以复制: https://github.com/jwz104/webflux-validation-test

Here is a repository so it can be reproducted: https://github.com/jwz104/webflux-validation-test

请求:

curl --request POST \
  --url http://localhost:8080/tickets \
  --header 'content-type: application/json' \
  --data '{
    "email": "",
    "name": "",
    "message": ""
}'

将联系人重命名为票证,但一切仍然相同.

Renamed contact to ticket, but everything is still the same.

推荐答案

在示例项目中放置的注释实际上是Ticket类的构造函数参数上的注释.对于Spring验证,您需要注释字段.您可以在Kotlin中使用注释使用地点目标.

The annotations you have placed in the example project are actually annotations on the constructor parameters of the Ticket class. For Spring validation, you need to annotate the fields instead. You can do this in Kotlin by using annotation use-site targets.

在这种情况下,您的Ticket类应如下所示:

In this specific case, your Ticket class should look like this:

data class Ticket(
        @field:Id
        @field:JsonSerialize(using = ToStringSerializer::class)
        val id: ObjectId = ObjectId.get(),

        @field:Email
        @field:Max(200)
        @field:NotEmpty
        val email: String,

        @field:NotEmpty
        @field:Size(min = 2, max = 200)
        val name: String,

        @field:NotEmpty
        @field:Size(min = 10, max = 2000)
        val message: String
)

此功能以及以下控制器功能将起作用,并按预期返回错误:

This, along with the following controller function will work and return errors as expected:

@PostMapping("tickets")
fun create(@RequestBody @Valid contact: Mono<Ticket>) : Mono<Ticket> {
    return contact.flatMap { ticketRepository.save(it) }
            .doOnError{ Error("test") }
}

这篇关于Spring Webflux bean验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆