Springboot 通过代码手动触发参数校验

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();
        //抽象类的实现类 processor方法的形参上添加 Validated注解,无效。
        // 为了让 Validated 注解生效,且实现动态控制
        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();
            
            // 手动触发参数校验,让jdk提供的 @NotNull注解等生效
            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);

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值