项目开发中会针对上游传过来的数据集中特定字段做一些校验

 

1.特定字段非空校验 @Validate @NotNull

@Immutable
@Data
public class MetaData{
  @Valid
  @NotNull
  private CommonMetaData commonMeta;
  @Valid
  @NotNull
  @Indexed
  private Integer businessDate;
  private Integer version=1;
  private Map<String, String> generatedFrom;
  private Long sourceTimestamp;
}
View Code
    public <T> void schemaValidate(SpecificRecordBase specificRecordBase){
        T t=getResult(specificRecordBase);
        if(null!=t) {
            Set<ConstraintViolation<T>> set = Validation.buildDefaultValidatorFactory().getValidator().validate(t); //针对t进行校验是否有空值
            List<String> errorList = new ArrayList<>();
            if (set != null && !set.isEmpty()) {
                for (ConstraintViolation<T> cv : set) {
                    String property = cv.getPropertyPath().toString();
                    StringBuilder sb = new StringBuilder();
                    sb.append(cv.getMessage());
                    errorList.add(property + ":" + sb);
                }
            }
            if (!CollectionUtils.isEmpty(errorList)) {
                throw new ValidateException(400, errorList.toString());
            }
        }else{
            throw new ValidateException(400,"Input Is Null");
        }
    }

    public <T> T getResult(SpecificRecordBase specificRecordBase) {
        return (T) gson.fromJson(specificRecordBase.toString(),BondQuoteData.class);
    }
View Code

 

2. 特定字段的特殊业务逻辑校验 @Constraint

2.1 Data:

@Data
public class VlaueData {
    @Valid
    @NotNull
    @ValueConstraint
    private String id;
}
View Code

2.2 controller:

controller层加上@Validate注解便可以实现对自定义注解字段的校验

  @ApiOperation(value = "Save a list of BondQuote by putting service.")
  @PutMapping(value = "/v2/xip/markets/quotes", consumes = {MediaType.APPLICATION_JSON_VALUE},
      produces = {MediaType.APPLICATION_JSON_VALUE})
  @ResponseStatus(HttpStatus.OK)
  public void validate(@RequestBody @Valid VlaueData vlaueData){
    constraintTest.valueProcess();
  }
View Code

 

2.3 自定义注解类 ValueConstraint  

这个类中定义校验类

@Documented
@Constraint(validatedBy = ValueValidate.class)
@Target({METHOD, FIELD, PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValueConstraint {
    String message() default
      "error input";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
View Code

 

2.4 校验类 ValueValidate

校验类实现 ConstraintValidator<ValueConstraint, String> 第一个参数对应2.3中自定义注解类,第二个参数对应2.1中要校验的参数类型

 

public class ValueValidate implements ConstraintValidator<ValueConstraint, String> {//第一个参数:@Interface自定义的注解类;第二个参数:要校验的数据类型
    public static final String specificBusinessDatePattern = "^(\\d{8})$";

    @Override
    public void initialize(ValueConstraint constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (!isIntValue(value)) {
            return false;
        }
        return true;
    }

    public boolean isIntValue(String string) {
        return string.matches(specificBusinessDatePattern);
    }
}
View Code

 

当输入参数满足2.4中isValid()返回false时,校验不通过,返回异常response

 

 

 

输入参数满足2.4中isValid()返回true时,校验通过继续往下走

 

posted on 2021-06-25 16:14  colorfulworld  阅读(1236)  评论(0编辑  收藏  举报