这是方案,带有注释的控制器@RestController和需要验证PUT其@RequestBody参数的方法。我@Valid在参数上使用了注释@NotNull,@Min在bean字段上使用了注释,但是它们不起作用。
@RestController
PUT
@RequestBody
@Valid
@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它仍然无法正常工作…
@Validated
有任何想法吗?
我想通了…这是因为PurchaseWrapperValidator实现的功能org.springframework.validation.Validator会覆盖默认javax.validation.*注释。
PurchaseWrapperValidator
org.springframework.validation.Validator
javax.validation.*