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

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

正常:

 

异常:

 

  1. 首先定义一个切面类:

@Aspect 用于声明一个类为切面

加在类上,如下:

@Aspect
@Component
public class AuthorizationAspect {
...
}
  1. 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorization {
    /**
     * 业务代码
     * @return
     */
    String[] businessType();
}
  1. 定义获取参数的方法
/**
     * 获取参数列表
     *
     * @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;
    }
  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);
        ...
        }
}
 
  1. 以上都定义好了之后,在需要验证的controller接口上加上自定义注解@Authorization,如下:
@Api(tags = {"接口"})
@RestController
@RequestMapping("test")
public class ResearchController {

    @Authorization(businessType = "6")
    @ApiOperation(value = "测试")
    @PostMapping("/get")
    public ResponseResult get(String id,@RequestBody List<Integer> sourceTypes){
       System.out.println(id);
        return new ResponseResult();
    }

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值