思想:
我们在某些业务场景下需要对接口的入参进行校验或者权限验证,因此需要获取接口的参数列表依次来支持我们的逻辑操作,因此需要我们获取接口的参数,下面是利用自定义注解配合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形式的请求参数了。