我在帶有 Webflux 的 Spring Boot 中有一個簡單的 REST API。我想在我的 POST 請求中對請求正文使用簡單的基于注釋的驗證。
配方模型.kt
package com.example.reactive.models
import org.springframework.data.annotation.Id
import org.springframework.data.relational.core.mapping.Table
import org.springframework.stereotype.Component
import javax.validation.constraints.Max
import javax.validation.constraints.NotBlank
@Table("recipes")
data class Recipe (
@Id
val id: Long?,
@NotBlank(message = "Title is required")
val title: String,
@Max(10, message = "Description is too long")
val description: String?,
)
RecipeRepo.kt
package com.example.reactive.repositories
import com.example.reactive.models.Recipe
import org.springframework.data.repository.reactive.ReactiveCrudRepository
import org.springframework.stereotype.Repository
@Repository
interface RecipeRepo : ReactiveCrudRepository<Recipe, Long>
配方控制器.kt
package com.example.reactive.controllers
import com.example.reactive.models.Recipe
import com.example.reactive.models.RecipeMapper
import com.example.reactive.repositories.RecipeRepo
import com.example.reactive.services.RecipeService
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import javax.validation.Valid
@RestController
@RequestMapping("/recipes")
class RecipeController(val recipeService : RecipeService) {
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun createRecipe(@RequestBody payload: @Valid Recipe): Mono<Recipe> =
recipeService.createRecipe(payload)
}
食譜服務.kt
package com.example.reactive.services
import com.example.reactive.models.Recipe
import com.example.reactive.models.RecipeMapper
import com.example.reactive.repositories.RecipeRepo
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Service
class RecipeService(val recipeRepo: RecipeRepo, val recipeMapper: RecipeMapper) {
fun createRecipe(recipe: Recipe): Mono<Recipe> = recipeRepo.save(recipe)
}
期望:當我提供一個帶有空字串作為標題和/或超過 10 個字符的描述的 POST 請求時,我不應該得到 201 CREATED 作為回應。
與郵遞員核對
如您所見,我收到了 201 CREATED 作為回應。
有沒有人看到我哪里出錯了???
uj5u.com熱心網友回復:
您需要在控制器(@Valid放置)中進行一些更改:
@RestController
@RequestMapping("/recipes")
class RecipeController(val recipeService : RecipeService) {
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun createRecipe(@RequestBody @Valid payload: Recipe): Mono<Recipe> =
recipeService.createRecipe(payload)
}
而且在模型本身(您需要使用@field:):
@Table("recipes")
data class Recipe (
@field:Id
val id: Long?,
@field:NotBlank(message = "Title is required")
val title: String,
@field:Max(10, message = "Description is too long")
val description: String?,
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363845.html
標籤:弹簧靴 休息 科特林 弹簧-webflux
上一篇:在類路徑資源[org/axonframework/springboot/autoconfig/AxonAutoConfiguration.class]中定義名稱為“commandGateway”的be
下一篇:ValueError:Input0oflayer"sequential"與層不兼容:expectedshape=(None,455,30),foundshape=(None,30)
