【发布时间】: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