参数校验碰到个场景:两个参数或者多个参数需要联合校验,不能都为空,即至少有一个有值
springboot提供的校验注解都无法满足,一般在controller写if判断

联合参数校验的注解需要group 条件触发才有效

  public Result<DepositActivityMixVO> depositMixDetail(@RequestBody @Valid DepositRequest request){
        //参数校验
        if(request.getIsRecommend() && Objects.isNull(request.getRecommendAmount())){
            return Result.failureData(BaseExceptionConstant.INVALID_ARGUMENT);
        }
  }     

springboot提供了自定义分组校验的功能, 可以避免在controller写if校验参数
实现步骤:

参数接受类添加自定义分组

@Data
@ApiModel
@GroupSequenceProvider(value = UserStoreSequenceProvider.class)
public class InnerUserStroedRequest implements Serializable {

    @ApiModelProperty(value = "充值金额")
    @NotNull(message = "充值金额不能为空", groups = WhenEntityIsNull.class)
    @Min(value = 1, message = "充值金额应该大于0", groups = WhenEntityIsNull.class)
    @Max(value = 100000, message = "充值金额不能大于10W", groups = WhenEntityIsNull.class)
    private BigDecimal amount;

    @ApiModelProperty(value = "储值规则")
    @Min(value = 1, message = "储值规则不正确", groups = WhenAmountIsNull.class)
    @NotNull(message = "储值规则不能为空", groups = WhenAmountIsNull.class)
    private Integer entity;

    /**
     * 储值金额没传
     */
    public interface WhenAmountIsNull {}

    /**
     * 储值规则没传
     */
    public interface WhenEntityIsNull {}

}

@GroupSequenceProvider(value = UserStoreSequenceProvider.class)
注解的作用可依据自定义的逻辑 动态的定义一个默认校验组,逻辑在指定的处理类实现即可

实现处理类,重写getValidationGroups方法

public class UserStoreSequenceProvider implements DefaultGroupSequenceProvider<InnerUserStroedRequest> {

    @Override
    public List<Class<?>> getValidationGroups(InnerUserStroedRequest innerUserStroedRequest) {
        List<Class<?>> defaultGroupSequence = new ArrayList<>();
        defaultGroupSequence.add(InnerUserStroedRequest.class);

        if(Objects.nonNull(innerUserStroedRequest)){
            //储值金额为null,group = WhenAmountIsNull 的校验注解生效
            if(Objects.isNull(innerUserStroedRequest.getAmount()) ){
                defaultGroupSequence.add(InnerUserStroedRequest.WhenAmountIsNull.class);
            }
            //储值规则为null,group = WhenEntityIsNull 的校验注解生效
            if(Objects.isNull(innerUserStroedRequest.getEntity())){
                defaultGroupSequence.add(InnerUserStroedRequest.WhenEntityIsNull.class);
            }
        }
        return defaultGroupSequence;
    }
}

同理 '当xxType值为A,paramA值必传。xxType值为B,paramB值必须传' 等类似这样的场景也可以用这个方法实现

over


 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐