本篇内容主要讲解“Spring Aop 怎么获取参数名参数值”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring Aop 怎么获取参数名参数值”吧!
有时候我们在用Spring Aop面向切面编程,需要获取连接点(JoinPoint)方法参数名、参数值。
Mac OSX
Intellij IDEA
Spring Boot 2x
Jdk 1.8x
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;
/**
* DemoAop
* Create by Gray(Ganguocai@outlook.com)
*/
@Aspect
@Component
@Slf4j
public class DemoAop {
/**
* 环绕通知
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@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集合
* @param joinPoint
* @return
*/
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;
}
}
一般来说,我们的参数,都是通过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);
}
{
"timeStamp": 21602756894612,
"status": 0,
"results": {
"userName": "yang20102",
"userLevel": "3"
},
"errorCode": null,
"errorMessage": null
}
到此,相信大家对“Spring Aop 怎么获取参数名参数值”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。