Spring Aop 如何獲取參數(shù)名參數(shù)值
有時候我們在用Spring Aop面向切面編程,需要獲取連接點(diǎn)(JoinPoint)方法參數(shù)名、參數(shù)值。
環(huán)境: Mac OSX Intellij IDEA Spring Boot 2x Jdk 1.8xCode: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@Slf4jpublic class DemoAop { /** * 環(huán)繞通知 * @param proceedingJoinPoint * @return * @throws Throwable */ @Around(value = 'execution(* com.example.aopdemo..*(..)))') public Object demoAop(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {log.debug('執(zhí)行前:');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(); //執(zhí)行連接點(diǎn)方法,object:方法返回值log.debug('執(zhí)行后:');return object; } /** * 獲取參數(shù)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; }}AOP切面獲取參數(shù)的一個小技巧
一般來說,我們的參數(shù),都是通過json傳遞的,那么這個問題就轉(zhuǎn)化成了,從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); // 獲取復(fù)雜對象 Object results = jsonObject.get('results'); JSONObject jsonObjectResults = JSON.parseObject(results.toString()); Object userName = jsonObjectResults.get('userName'); System.out.println('userName:' + userName);}實(shí)例json如下:
{ 'timeStamp': 21602756894612, 'status': 0, 'results': { 'userName': 'yang20102', 'userLevel': '3' }, 'errorCode': null, 'errorMessage': null}
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車2. ThinkPHP5 通過ajax插入圖片并實(shí)時顯示(完整代碼)3. Docker 容器健康檢查機(jī)制4. CSS3實(shí)現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效5. Python xml、字典、json、類四種數(shù)據(jù)類型如何實(shí)現(xiàn)互相轉(zhuǎn)換6. python中asyncio異步編程學(xué)習(xí)7. python os.listdir()亂碼解決方案8. Java struts2 package元素配置及實(shí)例解析9. ASP實(shí)現(xiàn)文件上傳的方法10. python使用openpyxl庫讀寫Excel表格的方法(增刪改查操作)
