dio*_*ato 7 spring spring-mvc bean-validation
我们正在使用SpringMVC创建一个RESTful API,我们有一个/ products端点,其中POST可用于创建新产品,PUT用于更新字段.我们还使用javax.validation来验证字段.
在POST工作正常,但在PUT中用户只能传递一个字段,我不能使用@Valid,所以我需要复制所有使用注释和Java代码进行PUT的验证.
任何人都知道如何扩展@Valid注释并创建像@ValidPresents或其他解决我的问题的东西?
您可以将验证组与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;
}
Run Code Online (Sandbox Code Playgroud)
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) { ... }
}
Run Code Online (Sandbox Code Playgroud)
有了这个代码后,Product.code
,Product.name
并Product.price
会在创建和更新的时间来验证. Product.quantity
但是,只有在更新时才会验证.
归档时间: |
|
查看次数: |
1577 次 |
最近记录: |