【Aop的基于xml配置】基于XML的AOP详情

基于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{
    
    // 后置通知
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值