@Aspect//作用是把当前类标识为一个切面供容器读取
@Component
public class InterfaceLogAspect {
//全路径是怕有重名的注解
@Around("@annotation(路径.InterfaceLog)")
public Object log(ProceedingJoinPoint pjp) throws Exception {
// 從切點上獲取目標方法
Method method = ((MethodSignature)pjp.getSignature()).getMethod();
//拿到注解
InterfaceLog interfaceLog = method.getAnnotation(InterfaceLog.class);
Object response = null;
long startTime = System.currentTimeMillis();
try {
// 目标方法执行
response = pjp.proceed();
} catch (Throwable throwable) {
throw new Exception(throwable);
}
long elapsedTime = System.currentTimeMillis()-startTime;
if (!StringUtils.isEmpty(interfaceLog.reqParamsName())) {
Map<String, Object> context = new HashMap<>();
// 获取参数值 返回执行目标方法时的参数值
Object[] args = pjp.getArgs();
// 获取运行时参数的名称
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(method);
}
注解
@Retention(RUNTIME)
public @interface InterfaceLog {}
启动类
@EnableAspectJAutoProxy
表示开启AOP代理自动配置,
开启注解支持