È possibile utilizzare i gruppi di convalida con l'annotazione Spring org.springframework.validation.annotation.Validated
.
Product.java
class Product {
/* Marker interface for grouping validations to be applied at the time of creating a (new) product. */
interface ProductCreation{}
/* Marker interface for grouping validations to be applied at the time of updating a (existing) product. */
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) { ... }
}
Con questo codice in atto, Product.code
, Product.name
e Product.price
verrà convalidato al momento della creazione e aggiornamento. Product.quantity
, tuttavia, verrà convalidato solo al momento dell'aggiornamento.