We are creating a RESTful API with SpringMVC and we have a /products end point where POST can be used to create a new product and PUT to update fields. We are also using javax.validation to validate fields.
In POST works fine, but in PUT the user can pass only one field, and I can't use @Valid, so I will need to duplicate all validations made with annotation with java code for PUT.
Anyone knows how to extend the @Valid annotation and creating something like @ValidPresents or something else that solve my problem?
You can use validation groups with the Spring org.springframework.validation.annotation.Validated
annotation.
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) { ... }
}
With this code in place, Product.code
, Product.name
and Product.price
will be validated at the time of creation as well as update. Product.quantity
, however, will be validated only at the time of update.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With