- 为了方便调试记录使用的参数,使用AOP将controller 以及service包下的方法做切面拦截所有的方法
package com.huifer.rpctest.aspect;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.management.loading.PrivateClassLoader;
import lombok.Data;
import lombok.ToString;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import sun.security.krb5.internal.PAData;
@Component
@Aspect
public class ControllerAspect {
@Pointcut("execution( * com.huifer.rpctest.controller.*.*(..) )")
public void aspController() {
}
@Pointcut("execution( * com.huifer.rpctest.service.*.*(..) )")
public void aspService() {
}
@AfterThrowing(pointcut = "aspController() || aspService()", throwing = "e")
public void getControllerParam(JoinPoint joinPoint, Exception e) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
String[] parameterNames = signature.getParameterNames();
Object[] args = joinPoint.getArgs();
List<MethodAndArgs> methodAndArgsList = new ArrayList<>();
if (parameterNames.length == args.length) {
for (int i = 0; i < parameterNames.length; i++) {
String parameterName = parameterNames[i];
Object arg = args[i];
MethodAndArgs methodAndArgs = new MethodAndArgs();
methodAndArgs.setParameterName(parameterName);
methodAndArgs.setArg(arg);
methodAndArgsList.add(methodAndArgs);
}
}
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
ControllerAop controllerAop = new ControllerAop();
controllerAop.setClassName(className);
controllerAop.setMethodName(methodName);
controllerAop.setMethodAndArgs(methodAndArgsList);
controllerAop.setTime(System.currentTimeMillis());
controllerAop.setException(e);
System.out.println(controllerAop);
}
@Data
@ToString
private static class MethodAndArgs {
private String parameterName;
private Object arg;
}
@Data
@ToString
private static class ControllerAop {
private String className;
private String methodName;
private List<MethodAndArgs> methodAndArgs = new ArrayList<>();
private Exception exception;
private long time;
}
}