【发布时间】:2020-11-16 00:36:35
【问题描述】:
在带注释的 MVC 控制器中使用以下验证设置:
@RestController
@RequestMapping("/users")
@Validated // <-- without this, the @Size annotation in setPassword() has no effect
public class UserController {
@PutMapping("/{id}/password")
public void setPassword(@PathVariable long id, @RequestBody @Size(min = 8) String password) {
/* ... */
}
@PutMapping("/{id}/other")
public void setOther(@PathVariable long id, @RequestBody @Valid MyFormObject form) {
/* ... */
}
}
控制器上的@Validated 是方法参数所必需的,因为它不是“复杂”对象。相比之下,setOther 方法上的@Valid 注释在没有@Validated 注释的情况下也能正常工作。
为什么需要@Validated?为什么不默认启用呢?使用它需要付费吗?
编辑
请注意,Difference between @Valid and @Validated in Spring 是相关的(我在问这个问题之前读过它),但它没有解决我的问题中的 why。
【问题讨论】:
标签: java spring spring-boot validation spring-mvc