环绕通知
问题
- 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了
分析
- 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们现在没有。
解决
-
Spring框架为我们提供了一个接口
ProceedingjoinPoint
。该接口有一个方法proceed()
,此方法就相当于明确调用切入点方法。 -
该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
理解
- 它是spring框架为我们提供的一种在代码中手动控制增强方法何时执行的方式
配置环绕通知
标签:aop:around
<aop:around method="aroundPrintLog" pointcut-ref="pt"></aop:around>
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--Spring的IOC配置:把service对象配置起来-->
<!--1. 有一个需要增强方法的service,需要加个日志-->
<bean id="accountService" class="cn.luis.service.impl.AccountServiceImpl"></bean>
<!--配置Logger类-->
<!--2. 写了一个日志的通知,它里面有加日志的方法-->
<bean id="logger" class="cn.luis.util.Logger"></bean>
<!--配置AOP-->
<aop:config>
<!--配置切入点表达式:写在aspect标签前面作用范围更大-->
<aop:pointcut id="pt" expression="execution( * cn.luis.service.impl.*.*(..))"/>
<!--配置切面-->
<!--3. 配置的这个切面引用了我们配置的通知2-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置环绕通知-->
<aop:around method="aroundPrintLog" pointcut-ref="pt"></aop:around>
</aop:aspect>
</aop:config>
</beans>
Java代码
步骤
- 得到方法执行所需的参数:
接口.getArgs()
Object[] args = pjp.getArgs();
- 明确调用业务层方法(切入点方法)
pjp.proceed(args);
-
抛出异常
catch (Throwable t)
-
获取调用业务层方法的返回值
代码:
记录日志的工具类
package cn.luis.util;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* @ClassName Logger
* @Description 用于记录日志的工具类,它里面提供了公共的代码
* @Author L
* @Date 2020.04.05 1:18
* @Version 1.0
* @Remark TODO
**/
public class Logger {
public Object aroundPrintLog(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
// 1.得到方法执行所需的参数
Object[] args = pjp.getArgs();
System.out.println("环绕通知开始记录日志...前置");
// 2.明确调用业务层方法(切入点方法),这里的异常要用 【throws Throwable】
rtValue = pjp.proceed(args);
System.out.println("环绕通知开始记录日志...后置");
// 3.返回值
return rtValue;
} catch (Throwable t) {
System.out.println("环绕通知开始记录日志...异常");
// 4.抛异常
throw new RuntimeException(t);
} finally {
System.out.println("环绕通知开始记录日志...最终");
}
}
}