本文基于
在SpringBoot中使用AOP

获取被被通知方法参数并传递给通知方法,主要有两种方式:

  • 使用JoinPoint获取:Spring AOP提供使用org.aspectj.lang.JoinPoint类型获取连接点数据,任何通知方法的第一个参数都可以是JoinPoint(环绕通知是ProceedingJoinPoint,JoinPoint子类),当然第一个参数位置也可以是JoinPoint.StaticPart类型,这个只返回连接点的静态部分。
  • 自动获取:通过切入点表达式(arg())可以将相应的参数自动传递给通知方法;

使用JoinPoint获取

也就是在通知的方法中,第一个参数使用JoinPoint 。(环绕通知是ProceedingJoinPoint,JoinPoint子类)

@Before(value = "printVisitLog()")
public void before(JoinPoint joinPoint) {
	log.info("目标对象:" + joinPoint.getTarget());
	log.info("目标方法:" + joinPoint.getSignature().getDeclaringTypeName() +"." + joinPoint.getSignature().getName());
	log.info("传入参数:" + Arrays.toString(joinPoint.getArgs()));
}

自动获取

@Pointcut(value = "execution(public * com.boco.fyk..controller..*.*(..)) && !within(com.boco.fyk.core.config.controller.*)" 
		+ " && args(userId,..)")
public void printVisitLog(String userId) {}

@Before(value = "printVisitLog(userId)")
public void before(String userId) {
	log.info("参数:" + userId);
}

在后置返回通知中获取返回值

在后置返回通知中获取返回值,只需要在@AfterReturning注解中,加入属性returning,值随便取。

@AfterReturning(value = "printVisitLog()", returning="v")
public void afterReturning(Object v) {
	log.info(v.toString());
}

在后置异常通知中获取异常

要在后置异常通知中,获取异常,只需要在@AfterThrowing注解中,加入属性throwing ,值随便取。

@AfterThrowing(value = "printVisitLog()", throwing = "e")
public void afterThrowing(Object e) {
	......
}

版权声明:本文为fyk844645164原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/fyk844645164/article/details/100314371