在SpringBoot中使用AOP——通知中的参数


本文基于 在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) {
	......
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值