基于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]配置文件
<!-- 将被代理的目标类加入IOC容器 -->
<bean id="calculator" class="com.spring.aop.target.Calculator"/>
<!-- 将切面类加入IOC容器 -->
<bean id="logAspect" class="com.spring.aop.aspect.LogAspect"/>
<!-- 配置AOP -->
<aop:config>
<!-- 声明切入点表达式 -->
<aop:pointcut id="logPointCut" expression="execution(* *..Calculator.*(..))"/>
<!-- 配置切面,使用ref属性引用切面类对应的bean。如有需要可以使用order属性指定当前切面的优先级数值 -->
<aop:aspect ref="logAspect">
<!-- 配置具体通知方法,通过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:aspect>
</aop:config>
[3]创建目标类
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;
}
}
[4]创建切面类
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());
}
}
关于五种通知的总结
try {
// 前置通知
// 目标方法
// 返回通知
}catch(Exception e){
// 异常通知
}finally{
// 后置通知
}