![](/img/trans.png)
[英]Spring (Boot) validation annotations for different layers on the same class
[英]Spring boot and Bean validation in different methods and the same class
我正在使用 spring boot 做一个 rest webservice,我想知道是否可以通过在控制器层中使用 POJO 作为参数的方法对 bean 验证注释进行不同的验证。
例子:
POJO:
Public class Person{
@NotNull(forMethod="methodOne")
private String firstName;
@NotNull(forMehotd="methodTwo")
private String lastName;
private String age;
//getter and setter
}
控制器
@RestController
public class controller{
@RequestMapping(....)
public ResponseEntity methodOne(@Valid @RequestBody Person person){
.....
}
@RequestMapping(....)
public ResponseEntity methodTwo(@Valid @RequestBody Person person){
......
}
}
我知道可以在方法中使用单独的参数来做到这一点,但是我有一个具有如此多属性的 POJO。 有可能做这样的事情吗?
我认为您应该在 bean 验证注释中使用validation groups
并使用@Validated
注释而不是@Valid
注释。 因为@Validated
注释有一个value
属性,它指定了一个用于验证的组。
例如:
Public class Person{
@NotNull(groups={MethodOne.class})
private String firstName;
@NotNull(groups={MethodTwo.class})
private String lastName;
private String age;
//getter and setter
}
和
@RestController
public class controller{
@RequestMapping(....)
public ResponseEntity methodOne(@Validated(MethodOne.class) @RequestBody Person person){
.....
}
@RequestMapping(....)
public ResponseEntity methodTwo(@Validated(MethodTwo.class) @RequestBody Person person){
......
}
}
顺便说一下,不要忘记您应该创建MethodOne
和MethodTwo
接口以将它们用作验证组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.