SpringMVC参数校验之校验集合中的字段

/**
 * @author Yangqi.Pang
 */
@RestController
@RequestMapping("/warehouse")
public class WarehouseAllocateController {

    @Autowired
    private WarehouseShipperService warehouseShipperService;


    @PostMapping("/allocate")
    public ApiResult<Object> allocate(@RequestBody AllocationReq allocationReq){
        //TODO 分仓规则
        return ApiResult.success();
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class AllocationReq {

        /**
         * 收货货主编号
         */
        private String storeShipperCode;

        /**
         * 发货货主编号
         */
        private String deliverShipperCode;

        /**
         * 订单类型
         */
        @NotNull(message = "订单类型")
        private OrderType orderType;

        /**
         * 货品明细
         */
        @NotEmpty(message = "货品明细不能为空")
        private List<GoodsDetail> goodsDetails;

    }

    @Getter
    @AllArgsConstructor
    public enum OrderType {

        /**
         * 入库单
         */
        STORE,

        /**
         * 出库单
         */
        DELIVER,

        /**
         * 调拨单
         */
        TRANSFER
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class GoodsDetail {

        /**
         * 货主货品编码
         */
        @NotBlank(message = "货主货品编码不能为空")
        private String shipperGoodsCode;

        /**
         * 批次号
         */
        private String batchNo;

        /**
         * 数量
         */
        @NotNull(message = "数量不能为空")
        private BigDecimal num;
    }
}

  如代码所示:如何在Controller层校验goodsDetails 所传的参数?

1.Controller层加@Validated注解

走单元测试校验参数:

public class WarehouseAllocateControllerTest extends BaseTest {

    @Autowired
    private WarehouseAllocateController warehouseAllocateController;

    @Test
    @DisplayName("分仓规则传参校验单元测试")
    public void testValidate(){
        WarehouseAllocateController.AllocationReq allocationReq = WarehouseAllocateController.AllocationReq.builder()
                .build();
        warehouseAllocateController.allocate(allocationReq);
    }

}

 校验结果:

我没有传参数,但是校验通过了,说明校验不起做用

2.方法层加@Validated 

 校验结果:

 还是能通过,说明校验还是不起作用

2.方法层加@Vaild

 校验结果:

校验不通过,说明校验有效

3.单元测试增加参数

 校验结果:

 校验通过,但有个问题是,我只是传了一个空的对象,没有校验集合里面的对象的属性:

 4.对象集合属性上加@Valid

 校验结果:

 校验不通过,说明校验有作用

总结:如果校验的对象是集合,而且还要校验的是集合里面的每个对象的属性时,就可以采用此种方式:Controller层加@Validated,方法层加@Valid, 集合属性上加@Valid 就可以实现完整校验;

原文地址:https://www.cnblogs.com/pangyangqi/p/14537011.html