问题描述
我们正在使用SpringMVC创建RESTful API,我们有一个/products端点,在其中可以使用POST来创建新产品,并使用PUT来更新字段.我们还使用javax.validation来验证字段.
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.
在POST中工作正常,但在PUT中,用户只能传递一个字段,而我不能使用@Valid,因此我将需要复制所有使用PUT的Java代码进行的注解验证.
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.
任何人都知道如何扩展@Valid批注并创建类似@ValidPresents之类的东西或解决我问题的其他东西吗?
Anyone knows how to extend the @Valid annotation and creating something like @ValidPresents or something else that solve my problem?
推荐答案
您可以将验证组与Spring org.springframework.validation.annotation.Validated
批注一起使用.
You can use validation groups with the Spring org.springframework.validation.annotation.Validated
annotation.
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;
}
@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
仅在更新时进行验证.
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.
这篇关于如何使用SpringMVC @Valid来验证POST中的字段,而不能验证PUT中的空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!