java @Valid 注释在 spring boot 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31175009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:14:05  来源:igfitidea点击:

@Valid annotation is not working in spring boot

javaspringvalidationspring-boot

提问by Ryan Zhu

Here is the scenario, a controller annotated with @RestControllerand a PUTmethod whose @RequestBodyargument needs to be validated. I use @Validannotation on the argument and @NotNull,@Minannotations on bean fields, but they are not working.

这是一个场景,一个用注释的控制器@RestController和一个需要验证参数的PUT方法@RequestBody。我@Valid在参数和 上使用注释@NotNull@Min对 bean 字段使用注释,但它们不起作用。

Code is here:

代码在这里:

the Bean:

豆:

public class PurchaseWrapper {
  @DecimalMin(value = "0.00",message = "discount must be positive")
  @NotNull
  private BigDecimal discount;
  @NotNull
  private Long merchandiseId;
  @NotNull
  private Long addressId;
  @Min(1)
  @NotNull
  private Integer count;
}

the Controller

控制器

@RestController
@RequestMapping("merchandises")
public class MerchandiseController {

@RequestMapping(value = "purchase",method = RequestMethod.PUT)
public ResponseEntity<RestEntity> purchase(@Valid @Validated @RequestBody PurchaseWrapper purchaseWrapper,
                                           @RequestParam String token){
    return new ResponseEntity<>(merchandiseService.purchase(purchaseWrapper,token),HttpStatus.OK);
}

@Autowired
PurchaseWrapperValidator purchaseWrapperValidator;

@InitBinder(value = "purchaseWrapper")
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(purchaseWrapperValidator);
}
}

The pom file:

pom 文件:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    <dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
    </dependency>

I have no idea what's wrong here... And I guess it's the problem that I use @Validand @Validatedannotations both on the same argument. But even though I omit the @Validatedannotation, the @Validis still not working...

我不知道这里出了什么问题......我想这是我在同一个论点上使用@Valid@Validated注释的问题。但即使我省略了@Validated注释,@Valid仍然无法正常工作......

Any ideas?

有任何想法吗?

回答by Ryan Zhu

I figured it out... it's because the PurchaseWrapperValidatorwhich implements org.springframework.validation.Validatoroverrides the default javax.validation.*annotations.

我想通了......这是因为PurchaseWrapperValidator它实现了org.springframework.validation.Validator覆盖默认javax.validation.*注释。