Java自定义注解验证非空参数

自定义注解的方式进行验证,分享一下,支持参数对象字段验证、参数字段验证,需要改验证规则也可以直接改,废话不多说,上代码

aop层

package com.abb.min.business.util.bean;


import com.abb.min.business.Exception.UsException;
import com.alibaba.druid.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;

@Aspect
@Component

/**
 * 功能描述: 参数校验
 * @param null:
 * @return:
 * @auther: nike
 * @date: 2020/07/05 17:19
 * @description:
 */
public class RequestRequireAspect {



    public RequestRequireAspect() {
    }

    @Pointcut("@annotation(com.abb.min.business.util.bean.RequestRequire)")
    public void parameterInteceptor() {
    }

    @Around("parameterInteceptor()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object[] argss = pjp.getArgs();
        MethodInvocationProceedingJoinPoint mjp = (MethodInvocationProceedingJoinPoint) pjp;
        MethodSignature signature = (MethodSignature) mjp.getSignature();
        Method methodd = signature.getMethod();
        RequestRequire  require = methodd.getAnnotation(RequestRequire.class);
        if(require.parameter()==Object.class){
            String classType = pjp.getTarget().getClass().getName();
            String methodName = pjp.getSignature().getName();
            // 参数值
            Object[] args = pjp.getArgs();
            Class<?>[] classes = new Class[args.length];
            for (int k = 0; k < args.length; k++) {
                if (args[k] instanceof MultipartFile || args[k] instanceof ServletRequest || args[k] instanceof ServletResponse) {
                    return null;
                }
                if (!args[k].getClass().isPrimitive()) {
                    Class s = args[k].getClass();
                    classes[k] = s == null ? args[k].getClass() : s;
                }
            }
            ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
            Method method = Class.forName(classType).getMethod(methodName, classes);
            String[] parameterNames = pnd.getParameterNames(method);
            for (int i = 0; i < parameterNames.length; i++) {
                if(args[i]==null||StringUtils.isEmpty(args[i].toString())){
                    throw new UsException("参数"+parameterNames[i]+"不允许为空");
                }
            }
            return pjp.proceed();
        }
        String fieldNames=require.require().replace(",", ",");
        Object parameter=null;
        for(Object pa:argss){
            //class相等表示是同一个对象
            if (pa.getClass()==require.parameter() ) {
                parameter=pa;
            }
        }
        Class cl=parameter.getClass();
        for(String fieldName:fieldNames.split(",")){
            Field f=cl.getDeclaredField(fieldName);
            f.setAccessible(true);
            Object value=f.get(parameter);
            if(value==null||StringUtils.isEmpty(value.toString())){
              throw new UsException("参数"+fieldName+"不允许为空");
            }
        }
        //放行
        return pjp.proceed();
    }
}

定义自定义注解

package com.abb.min.business.util.bean;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author nike
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RequestRequire {

    /**
     * 接口所需要验证参数,小写逗号隔开
     */
    String require() default "";

    /**
     *传递参数的对象类型
     */
    Class<?> parameter() default Object.class;
}

大功告成~直接注解到方法上即可
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值