【发布时间】:2022-01-01 03:15:49
【问题描述】:
我在带有 Webflux 的 Spring Boot 中有一个简单的 REST API。 我想在我的 POST 请求中对请求正文使用基于注释的简单验证。
RecipeModel.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>
RecipeController.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)
}
RecipeService.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 作为响应。
有人看到我哪里出错了吗???
【问题讨论】:
-
你可以尝试将
@Validated添加到控制器中
标签: spring-boot rest kotlin spring-webflux