Spring Aop 如何獲取參數(shù)名參數(shù)值
有時(shí)候我們?cè)谟肧pring 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ù)的一個(gè)小技巧
一般來說,我們的參數(shù),都是通過json傳遞的,那么這個(gè)問題就轉(zhuǎn)化成了,從json中獲取指定字符串的問題。
OK,這個(gè)問題就簡單了。
如下: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ù)雜對(duì)象 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}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法4. Springboot 全局日期格式化處理的實(shí)現(xiàn)5. idea配置jdk的操作方法6. python 浮點(diǎn)數(shù)四舍五入需要注意的地方7. Docker容器如何更新打包并上傳到阿里云8. VMware中如何安裝Ubuntu9. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法10. JAMon(Java Application Monitor)備忘記
