思想:
??我們在某些業(yè)務場景下需要對接口的入參進行校驗或者權限驗證,因此需要獲取接口的參數列表依次來支持我們的邏輯操作,因此需要我們獲取接口的參數,下面是利用自定義注解配合Aop來實現的一個思路:
- 首先定義一個切面類:
@Aspect 用于聲明一個類為切面
加在類上,如下:
@Aspect
@Component
public class AuthorizationAspect {
...
}
- 自定義注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorization {
/**
* 業(yè)務代碼
* @return
*/
String[] businessType();
}
- 定義獲取參數的方法
/**
* 獲取參數列表
*
* @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;
}
- 定義Aop融撞,進行注解掃描
@Aspect
@Component
public class AuthorizationAspect {
/**
定義切點
*/
@Pointcut("@annotation(Authorization)")
public void executeService() {}
/**
環(huán)繞織入
*/
@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);
...
}
}
- 以上都定義好了之后,在需要驗證的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();
}
這樣在請求接口的時候粗蔚,我們就能拿到請求參數列表