这是场景,一个控制器注释为@RestController
and a PUT
方法,其@RequestBody
论证需要得到验证。我用@Valid
参数上的注释和@NotNull
,@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
and @Validated
注释都在同一个参数上。但即使我省略了@Validated
注释,将@Valid
仍然无法正常工作...
有任何想法吗?
我明白了...这是因为PurchaseWrapperValidator
它实现了org.springframework.validation.Validator
覆盖默认值javax.validation.*
注释。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)