- 要在增强方法里访问目标方法的参数和其他相关信息,可以讲增强方法的以一个形参以JointPoint类传入,对于Around来说,ProceedingJoinPoint就是JointPoint的子类了。
- JoitPoint提供了四个方法可以访问目标方法的相关信息
getArgs() 获得目标方法运行时候的参数 Signature getSignature() 获得被增强方法的相关信息 Object getTatget() 获得被增强方法的目标对象 Object getThis() 获得AOP框架生成的代理对象 - 下面是一个例子,使用了四种注解,并且在每一种注解中都访问了目标方法的相关信息
package pointcut_package; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import java.util.Arrays; @Aspect public class FourAdvice { @Around("execution( * pointcut_package.*.* (..))") public Object processTx(ProceedingJoinPoint proceedingJoinPoint) throws java.lang.Throwable{ System.out.println(" FourAdvice around增强, 方法执行之前"); Object[] args = proceedingJoinPoint.getArgs(); if(args != null && args.length >0 && args[0].getClass() == String.class) { args[0] = "增加的前缀" + args[0]; } Object rvt = proceedingJoinPoint.proceed(args); System.out.println("around 增强,方法执行之后"); if(rvt != null && rvt instanceof Integer){ rvt = (Integer)rvt * (Integer)rvt; } return rvt; } @Before("execution(* pointcut_package.*.* (..))") public void authority(JoinPoint joinPoint){ System.out.println("before增强,方法执行之前"); System.out.println("before,被织入增强的目标方法为" + joinPoint.getSignature().getName()); System.out.println("before, 被织入增强的目标方法参数为" + joinPoint.getArgs()); System.out.println("before, 被织入增强的目标方法对应的目标对象为" + joinPoint.getTarget()); } @AfterReturning(pointcut = "execution(* pointcut_package.*.*(..))", returning = "rvt") public void log(JoinPoint joinPoint, Object rvt){ System.out.println("afterReturning ,获取目标方法的返回值" + rvt); System.out.println("afterReturning,模拟记录日志" + joinPoint.getSignature().getName()); System.out.println("afterReturning, 目标方法的参数为" + joinPoint.getArgs()); System.out.println("afterReturinig, 目标方法的对应的对象为" + joinPoint.getTarget()); } @After( "execution( * pointcut_package.*.*(..))" ) public void release(JoinPoint joinPoint){ System.out.println("after, 模拟方法结束之后释放资源"); System.out.println("after, 被织入的方法是" + joinPoint.getSignature().getName()); System.out.println("after, 被织入目标方法的参数是 " + Arrays.toString(joinPoint.getArgs())); System.out.println("after, 被织入方法对应的目标对象是" + joinPoint.getTarget()); } }
其他的类和测试类和上上篇博文是一样的~
@AfterReturning(pointcut = "execution(* pointcut_package.*.*(..)) && args(arg0, arg1)", returning = "rvt") // 在定义要执行那些方法的时候就指定了目标方法要有两个实参 public void log(JoinPoint joinPoint, Object rvt,String arg0, String arg1){ // 这里就直接用啦~ System.out.println( "arg0和arg1:" + arg0 + "," + arg1); System.out.println("afterReturning ,获取目标方法的返回值" + rvt); System.out.println("afterReturning,模拟记录日志" + joinPoint.getSignature().getName()); System.out.println("afterReturning, 目标方法的参数为" + joinPoint.getArgs()); System.out.println("afterReturinig, 目标方法的对应的对象为" + joinPoint.getTarget()); }
-
还有一种方法是在注解中写参数(这么说很不专业,但是我觉得真的是这样,书上说的很是绕口)。这个直接在代码里说把
-
还有就是在方法执行之后的增强处理,就是把Before换成After就好了,原理是一样的,就不贴代码了。