如何使用SpringMVC @Valid来验证POST中的字段,而不是PUT中的空字段

dio*_*ato 7 spring spring-mvc bean-validation

我们正在使用SpringMVC创建一个RESTful API,我们有一个/ products端点,其中POST可用于创建新产品,PUT用于更新字段.我们还使用javax.validation来验证字段.

在POST工作正常,但在PUT中用户只能传递一个字段,我不能使用@Valid,所以我需要复制所有使用注释和Java代码进行PUT的验证.

任何人都知道如何扩展@Valid注释并创建像@ValidPresents或其他解决我的问题的东西?

man*_*ish 7

您可以将验证组与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.nameProduct.price会在创建和更新的时间来验证. Product.quantity但是,只有在更新时才会验证.