基于 XML 的 AOP

① 搭建环境

[1]加入 jar 包

com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.3.jar
hamcrest-core-1.3.jar
junit-4.12.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar

[2]配置文件

applicationContext.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!-- 将被代理的目标类加入IOC容器 -->
<bean id="calculator" class="com.atguigu.aop.component.target.Calculator"/>

<!-- 将切面类加入IOC容器 -->
<bean id="logAspect" class="com.atguigu.aop.component.aspect.LogAspect"/>

<!-- 配置AOP -->
<aop:config>

<!-- 声明切入点表达式 -->
<aop:pointcut id="logPointCut" expression="execution(* *..*.*(..))"/>

<!-- 配置切面,使用ref属性引用切面类对应的bean。如有需要可以使用order属性指定当前切面的优先级数值 -->
<aop:aspect ref="logAspect">

<!-- 配置通知方法:前置通知 -->
<!-- 使用method属性指定切面类中,哪一个方法是前置通知方法 -->
<!-- 使用pointcut-ref属性引用切入点表达式 -->
<aop:before method="doBefore" pointcut-ref="logPointCut"/>

<!-- 配置通知方法:返回通知 -->
<!-- 使用returning属性指定通知方法中接收目标方法返回值的形参名称 -->
<aop:after-returning method="doReturn" pointcut-ref="logPointCut" returning="result"/>

<!-- 配置通知方法:异常通知 -->
<!-- 使用throwing属性指定通知方法中接收目标方法异常对象的形参名称 -->
<aop:after-throwing method="doException" pointcut-ref="logPointCut" throwing="throwable"/>

<!-- 配置通知方法:后置通知 -->
<aop:after method="doAfter" pointcut-ref="logPointCut"/>

<!-- 配置通知方法:环绕通知 -->
<!--<aop:around method="doAfter" pointcut-ref="logPointCut"-->

</aop:aspect>

</aop:config>

② 创建目标类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Calculator {
public void add(int a, int b) {
System.out.println("(a+b) = " + (a+b));
}

public void sub(int a, int b) {
System.out.println("(a-b) = " + (a-b));
}

public void mul(int a, int b) {
System.out.println("(a×b) = " + (a*b));
}

public int div(int a, int b) {
System.out.println("(a÷b) = " + (a/b));
return a / b;
}
}

③ 创建切面类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class LogAspect {

public void doBefore(JoinPoint joinPoint) {
System.out.println("前置通知 " + joinPoint.getSignature().getName());
}

public void doReturn(JoinPoint joinPoint, Object result) {
System.out.println("返回通知 " + joinPoint.getSignature().getName() + " 返回值:" + result);
}

public void doException(JoinPoint joinPoint, Throwable throwable) {
System.out.println("异常通知 " + joinPoint.getSignature().getName() + " 异常:" + throwable.getClass().getName());
}

public void doAfter(JoinPoint joinPoint) {
System.out.println("后置通知 " + joinPoint.getSignature().getName());
}

}