项目开发中会针对上游传过来的数据集中特定字段做一些校验
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; }
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); }
2. 特定字段的特殊业务逻辑校验 @Constraint
2.1 Data:
@Data public class VlaueData { @Valid @NotNull @ValueConstraint private String id; }
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(); }
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 {}; }
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); } }
当输入参数满足2.4中isValid()返回false时,校验不通过,返回异常response
输入参数满足2.4中isValid()返回true时,校验通过继续往下走