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

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

  1. 首先定义一个切面类:
【Springboot|Springboot AOP利用反射获取请求参数】@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 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 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 fieldsName = getFieldsName(thisJoinPoint); ... } }

  1. 以上都定义好了之后,在需要验证的controller接口上加上自定义注解@Authorization,如下:
@Api(tags = {"接口"}) @RestController @RequestMapping("test") public class ResearchController {@Authorization(businessType = "6") @ApiOperation(value = "https://www.it610.com/article/测试") @PostMapping("/get") public ResponseResult get(String id,@RequestBody List sourceTypes){ System.out.println(id); return new ResponseResult(); }

这样在请求接口的时候,我们就能拿到请求参数列表

    推荐阅读