前言:
有时候我们在用Spring Aop面向切面编程,需要获取连接点(JoinPoint)方法参数名、参数值。
环境:
- Mac OSX
- Intellij IDEA
- Spring Boot 2x
- Jdk 1.8x
Code:
package com.example.aopdemo.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Aspect
@Component
@Slf4j
public class DemoAop {
@Around(value = "execution(* com.example.aopdemo..*(..)))")
public Object demoAop(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
log.debug("执行前:");
Map<String, Object> params = getNameAndValue(proceedingJoinPoint);
for (Map.Entry<String, Object> entry : params.entrySet()) {
System.out.println("name: " + entry.getKey() + " value: " + entry.getValue());
}
Object object = proceedingJoinPoint.proceed(); //执行连接点方法,object:方法返回值
log.debug("执行后:");
return object;
}
Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
Map<String, Object> param = new HashMap<>();
Object[] paramValues = joinPoint.getArgs();
String[] paramNames = ((CodeSignature)joinPoint.getSignature()).getParameterNames();
for (int i = 0; i < paramNames.length; i++) {
param.put(paramNames[i], paramValues[i]);
}
return param;
}
}
AOP切面获取参数的一个小技巧
一般来说,我们的参数,都是通过json传递的,那么这个问题就转化成了,从json中获取指定字符串的问题。
OK,这个问题就简单了。
如下:
public static void main(String[] args) {
// 这里JSONObject是fastjson-1.2.41.jar包下的
JSONObject jsonObject = JSON.parseObject("{\"timeStamp\":21602756894612,\"status\":0,\"results\":{\"userName\":\"yang20102\",\"userLevel\":\"3\"},\"errorCode\":null,\"errorMessage\":null}");
// 获取json最外层字符串
Object timeStamp = jsonObject.get("timeStamp");
System.out.println("timeStamp:" + timeStamp);
// 获取复杂对象
Object results = jsonObject.get("results");
JSONObject jsonObjectResults = JSON.parseObject(results.toString());
Object userName = jsonObjectResults.get("userName");
System.out.println("userName:" + userName);
}
实例json如下:
{
"timeStamp": 21602756894612,
"status": 0,
"results": {
"userName": "yang20102",
"userLevel": "3"
},
"errorCode": null,
"errorMessage": null
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。