Springboot AOP利用反射获取请求参数

思想:
  我们在某些业务场景下需要对接口的入参进行校验或者权限验证,因此需要获取接口的参数列表依次来支持我们的逻辑操作,因此需要我们获取接口的参数,下面是利用自定义注解配合Aop来实现的一个思路:
  
1.定义Aop,进行注解扫描:

@Aspect
@Component
public class AuthorizationAspect {
    /**
    定义切点
    */
    @Pointcut("@annotation(Authorization)")
    public void executeService() {}
    
    /**
    环绕织入    
    */
    @Around("executeService()")
    public Object proceed(ProceedingJoinPoint thisJoinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
        Method method = signature.getMethod();
        Authorization authCode = method.getAnnotation(Authorization.class);
        Object[] args = thisJoinPoint.getArgs();
        //获取到请求参数
        Map<String, Object> fieldsName = getFieldsName(thisJoinPoint);
        ...
        }
}
 

2.定义获取参数的方法

/**
     * 获取参数列表
     *
     * @param joinPoint
     * @return
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     */
    private static Map<String, Object> getFieldsName(ProceedingJoinPoint joinPoint) {
        // 参数值
        Object[] args = joinPoint.getArgs();
        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String[] parameterNames = pnd.getParameterNames(method);
        Map<String, Object> paramMap = new HashMap<>(32);
        for (int i = 0; i < parameterNames.length; i++) {
            paramMap.put(parameterNames[i], args[i]);
        }
        return paramMap;
    }

通过以上就可以获得key-value形式的请求参数了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

初夏0811

你的鼓励将是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值