软件编程
位置:首页>> 软件编程>> java编程>> Spring Aop 如何获取参数名参数值

Spring Aop 如何获取参数名参数值

作者:小动物不困i  发布时间:2022-09-08 17:00:41 

标签:Spring,Aop,参数名,参数值

前言:

有时候我们在用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;

/**
* 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;
   }
}

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
}

来源:https://blog.csdn.net/weixin_39931896/article/details/83451311

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com