在 spring-aop 的 基础使用(啥是增强类、切点、切面) 的基础上,
这里讲如何,在 增强类 的方法中,获取 目标方法 的一些信息
目录结构,
新增加了一个 MyAdvice类

新增加一个 MyAdvice类
java
package com.english.advice;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.lang.reflect.Modifier;
/**
* 在 增强类 的方法中,获取,目标方法的信息
*
* 1、获取,目标方法的方法名、参数、访问修饰符、所属的类信息
* 在 增强方法 添加 JoinPoint joinPoint 参数,
* JoinPoint 就包含了目标方法的信息
*
* 2、获取,目标方法的返回结果
* 只有 @AfterReturning 能获取 目标方法 的返回结果
* @AfterReturning(value = "execution(* com..impl.*.*(..))", returning = "myret")
* public void afterReturning(JoinPoint joinPoint, Object myret)
*
* 3、获取,目标方法的异常信息
* @AfterThrowing(value = "execution(* com..impl.*.*(..))", throwing = "mythrowable")
* public void afterThrowing(JoinPoint joinPoint, Throwable mythrowable)
*
*/
@Aspect
@Component
public class MyAdvice {
@Before("execution(* com..impl.*.*(..))")
public void before(JoinPoint joinPoint) {
// 获取方法属于的类的信息
String simpleName = joinPoint.getTarget().getClass().getSimpleName();
System.out.println("simpleName=" + simpleName);
// 获取访问修饰符
int modifiers = joinPoint.getSignature().getModifiers(); // int类型
String s = Modifier.toString(modifiers); // 将 int 转换为 对应的字符串
// 获取方法名
String name = joinPoint.getSignature().getName();
System.out.println("name= " + name);
// 获取目标方法的参数
Object[] args = joinPoint.getArgs();
}
@AfterReturning(value = "execution(* com..impl.*.*(..))", returning = "ret")
public void afterReturning(JoinPoint joinPoint, Object ret) {
}
@AfterThrowing(value = "execution(* com..impl.*.*(..))", throwing = "throwable")
public void afterThrowing(JoinPoint joinPoint, Throwable throwable) {
}
@After("execution(* com..impl.*.*(..))")
public void after(JoinPoint joinPoint) {
System.out.println("after");
}
}