@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.