1 用在controller上,请求参数可以使用校验
@Validated
public class TestController {
test(@Min(10) @PathVariable("id") Long id)
}
2 直接用在请求参数上,实体类中可以使用校验
public class TestController {
test(@Validated @RequestBody Entity entity)
}
public class Entity {
@NotNull(message = "price不能为空")
private BigDecimal price;
@NotBlank(message = "type不能为空")
private String type;
}
嵌套校验
请求参数上仍然需要加@Validated
public class TestController {
test(@Validated @RequestBody QTEntity qtentity)
}
被嵌套的参数需要加@Valid
public class QTEntity {
@NotBlank(message = "name不能为空")
private String name;
@Valid // 加上 否则嵌套无用
private Entity entity;
}
嵌套的实体类中正常使用校验
public class Entity {
@NotNull(message = "price不能为空")
private BigDecimal price;
}
分组校验
声明两个随意接口,用来代表组。(无任何意义的空接口,只为了分组)
public interface group1 {}
public interface group2 {}
@Validated与分组绑定
public class TestController {
// 使用分组1
test1(@Validated(@Validated({group1.class}) @RequestBody Entity entity)
// 使用分组2
test2(@Validated(@Validated({group2.class}) @RequestBody Entity entity)
}
校验时与分组绑定
public class Entity {
// 不绑定
@NotBlank(message = "good不能为空")
private String good;
// 与分组1绑定
@NotNull(message = "price不能为空",groups = {group1.class})
private BigDecimal price;
// 与分组2绑定
@NotBlank(message = "type不能为空",groups = {group2.class})
private String type;
}
- 不指定分组时候,属于默认分组
- 若指定分组,那么必须分组对应才会生效。
// test1(使用分组校验1)
==>
{
"good": "",
"price":"",
"type": ""
}
<==
{
"code": -1,
"message": "price不能为空"
}
// test1(使用分组校验1),其他两个校验并没有生效
==>
{
"good": "",
"price":1,
"type": ""
}
<==
{
"code": 0,
"message": "成功",
"result": true
}
如图想要默认分组也有效则可以这么写
public class TestController {
// 使用分组1和默认分组
test1(@Validated(@Validated({group1.class, Default.class}) @RequestBody Entity entity)
}
==>
{
"good": "",
"price":1,
"type": ""
}
<==
{
"code": -1,
"message": "good不能为空"
}
校验常用方法
@Validated 常用的注解



