You can use validation groups with Spring annotation org.springframework.validation.annotation.Validated .
Product.java
class Product { interface ProductCreation{} interface ProductUpdate{} @NotNull(groups = { ProductCreation.class, ProductUpdate.class }) private String code; @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) { ... } }
When using this code, Product.code , Product.name and Product.price will be checked during creation as well as updates. Product.quantity , however, will only be checked during the upgrade.
source share