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
@Valid annotation is not working in spring boot
提问by Ryan Zhu
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.
这是一个场景,一个用注释的控制器@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 @Valid
and @Validated
annotations both on the same argument. But even though I omit the @Validated
annotation, the @Valid
is still not working...
我不知道这里出了什么问题......我想这是我在同一个论点上使用@Valid
和@Validated
注释的问题。但即使我省略了@Validated
注释,@Valid
仍然无法正常工作......
Any ideas?
有任何想法吗?
回答by Ryan Zhu
I figured it out... it's because the PurchaseWrapperValidator
which implements org.springframework.validation.Validator
overrides the default javax.validation.*
annotations.
我想通了......这是因为PurchaseWrapperValidator
它实现了org.springframework.validation.Validator
覆盖默认javax.validation.*
注释。