@Valid 注释在 spring boot 中不起作用 [英] @Valid annotation is not working in spring boot

查看:87
本文介绍了@Valid 注释在 spring boot 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is the scenario, a controller annotated with @RestController and a PUT method whose @RequestBody argument needs to be validated. I use @Valid annotation on the argument and @NotNull,@Min annotations on bean fields, but they are not working.

代码在这里:

豆子:

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 仍然不起作用......

I have no idea what's wrong here... And I guess it's the problem that I use @Valid and @Validated annotations both on the same argument. But even though I omit the @Validated annotation, the @Valid is still not working...

有什么想法吗?

推荐答案

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

I figured it out... it's because the PurchaseWrapperValidator which implements org.springframework.validation.Validator overrides the default javax.validation.* annotations.

这篇关于@Valid 注释在 spring boot 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆