Spring Aop 如何獲取參數名參數值
有時候我們在用Spring Aop面向切面編程,需要獲取連接點(JoinPoint)方法參數名、參數值。
環境: 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([email protected]) */@Aspect@Component@Slf4jpublic 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; }}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}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: