您可以对约束进行分组,以便您可以确定在每种情况下要验证哪些属性。第一步是将属性添加groups
到您的javax验证注释中。为此,您需要为每个用例创建一些标记接口:
public interface MethodA { } // You should name this properly, it is just for demonstration purposes
public interface MethodB { }
然后您需要groups
在注释中配置属性:
@Data
public class ProductRequest {
@NotEmpty(groups = MethodA.class)
private String code;
@NotEmpty(groups = MethodB.class)
private String name;
}
最后一步是使用@Validated
代替@Valid
来触发数据验证。大致如下:
@RequestMapping(value = "/methodA", method = RequestMethod.POST)
public String methodA(@Validated(MethodA.class) @RequestBody ProductRequest productRequest) {
(...)
}
@RequestMapping(value = "/methodB", method = RequestMethod.POST)
public String methodB(@Validated(MethodB.class) @RequestBody ProductRequest productRequest) {
(...)
}
您可以在以下在线资源中阅读更多相关信息: