您可以将验证组与Spring
org.springframework.validation.annotation.Validated批注一起使用。
产品.java
class Product { interface ProductCreation{} interface ProductUpdate{} @NotNull(groups = { ProductCreation.class, ProductUpdate.class }) private String pre; @NotNull(groups = { ProductCreation.class, ProductUpdate.class }) private String name; @NotNull(groups = { ProductCreation.class, ProductUpdate.class }) private BigDecimal price; @NotNull(groups = { ProductUpdate.class }) private long quantity = 0;}ProductController.java
@RestController@RequestMapping("/products")class ProductController { @RequestMapping(method = RequestMethod.POST) public Product create(@Validated(Product.ProductCreation.class) @RequestBody Product product) { ... } @RequestMapping(method = RequestMethod.PUT) public Product update(@Validated(Product.ProductUpdate.class) @RequestBody Product product) { ... }}有了这个代码后,
Product.pre,
Product.name并
Product.price会在创建和更新的时间来验证。
Product.quantity,但是仅在更新时进行验证。



