Springboot 通过代码手动触发参数校验
public abstract class AbstractDaysTransferProcessor<T> {
@Override
public T assemble(JSONObject jsonObj){
Convertor<JSONObject> convertor1 = new Convertor<>();
convertor1.setParam(jsonObj);
Type type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Convertor<T> convertor = JSONObject.parseObject(JSON.toJSONString(convertor1),
new TypeReference<Convertor<T>>(type) {},
JSONReader.Feature.FieldBased);
T param = convertor.getParam();
Method method = ReflectionUtils.findMethod(this.getClass(), "processor",(Class<?>) type);
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Validated validated = null;
for (Annotation[] parameterAnnotation : parameterAnnotations) {
for (Annotation annotation : parameterAnnotation) {
if(annotation.annotationType().equals(Validated.class)){
validated = (Validated) annotation;
}
}
}
if(validated != null){
Class<?>[] groups = validated.value();
try(ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory()){
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<T>> violations = validator.validate(param,groups);
if(!violations.isEmpty()){
throw new ConstraintViolationException(violations);
}
}
}
return param;
}
@Transactional(rollbackFor = Exception.class)
@Override
public abstract boolean processor(T t);
}