【问题标题】:@Valid annotation is not working in spring boot@Valid 注解在 Spring Boot 中不起作用
【发布时间】:2015-07-02 03:13:52
【问题描述】:

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

代码在这里:

豆子:

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;
}

控制器

@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);
}
}

pom 文件:

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

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

有什么想法吗?

【问题讨论】:

    标签: java spring validation spring-boot


    【解决方案1】:

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

    【讨论】:

    • 提醒自己..你应该使用binder.**addValidators**(new PurchaseWrapperValidator());
    【解决方案2】:

    在 pom.xml 中添加一个依赖项。或者,在 start.spring.io 中选择 Validation on dependencies。

    依赖: groupId org.springframework.boot groupId artifactId spring-boot-starter-validation artifactId

    【讨论】:

      猜你喜欢
      • 2018-07-14
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2022-01-01
      • 2017-10-04
      • 1970-01-01
      • 2019-09-18
      相关资源
      最近更新 更多