1:引入相关依赖
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency>2:在entity class的属性上加上对应的注解
@ToString public class OrderRecord { private Integer id; @NotEmpty private String orderNo; private String orderType;3:在controller请求参数里面使用@Validated 注解,并且加入如果参数值不合法,那么对应的错误结果绑定判断BindingResult
@PostMapping(value = "/validate") public BaseResponse insert(@RequestBody @Validated OrderRecord orderRecord, BindingResult result) { BaseResponse response = new BaseResponse(StatusCode.Success); try { log.info("接收到的前端数据是" + orderRecord.toString()); // if ( StringUtils.isNullOrEmpty(orderRecord.getOrderNo())||orderRecord.getOrderType()== null) { // return new BaseResponse(StatusCode.InvalidParam); // } if(result.hasErrors()){ return new BaseResponse(StatusCode.InvalidParam); } } catch (Exception e) { response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage()); } return response; }