基于 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
| <bean id="calculator" class="com.atguigu.aop.component.target.Calculator"/>
<bean id="logAspect" class="com.atguigu.aop.component.aspect.LogAspect"/>
<aop:config>
<aop:pointcut id="logPointCut" expression="execution(* *..*.*(..))"/>
<aop:aspect ref="logAspect">
<aop:before method="doBefore" pointcut-ref="logPointCut"/>
<aop:after-returning method="doReturn" pointcut-ref="logPointCut" returning="result"/>
<aop:after-throwing method="doException" pointcut-ref="logPointCut" throwing="throwable"/>
<aop:after 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()); }
}
|