如何使用SpringMVC @Valid来验证POST中的字段,而不能验证PUT中的空字段
问题内容:
我们正在使用SpringMVC创建RESTful API,我们有一个/
products端点,在其中可以使用POST来创建新产品,并使用PUT来更新字段。我们还使用javax.validation来验证字段。
在POST中可以正常工作,但是在PUT中,用户只能传递一个字段,而我不能使用@Valid,因此我将需要复制所有使用PUT的Java代码进行的注解验证。
任何人都知道如何扩展@Valid批注并创建类似@ValidPresents之类的东西或解决我问题的其他东西吗?
问题答案:
您可以将验证组与Spring org.springframework.validation.annotation.Validated
批注一起使用。
产品.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) { ... }
}
有了这个代码后,Product.code
,Product.name
并Product.price
会在创建和更新的时间来验证。
Product.quantity
,但是仅在更新时进行验证。