前言:
有时候我们在用Spring Aop面向切面编程,需要获取连接点(JoinPoint)方法参数名、参数值。
环境:
- Mac OSX
- Intellij IDEA
- Spring Boot 2x
- Jdk 1.8x
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
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,这个问题就简单了。
如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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如下:
1
2
3
4
5
6
7
8
9
10
|
{ "timeStamp" : 21602756894612 , "status" : 0 , "results" : { "userName" : "yang20102" , "userLevel" : "3" }, "errorCode" : null , "errorMessage" : null } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_39931896/article/details/83451311