这是场景,一个用@RestController
注释的控制器和一个PUT
方法,其@RequestBody
参数需要验证。我在参数和@NotNull
上使用@Valid
注释,@Min
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;
}
控制者
@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
仍然不起作用......
有什么想法吗?
我想通了...这是因为实现org.springframework.validation.Validator
的PurchaseWrapperValidator
会覆盖默认的javax.validation.*
批注。
在pom.xml放置一个依赖项。或者,在 start.spring.io 选择"依赖项验证"。
屬地:groupId org.springframework.boot groupIdartifactId spring-boot-starter-validation artifactId