spring aop 的五种通知类型

本文转自:http://blog.csdn.net/cqabl/article/details/46965197

spring aop通知(advice)分成五类: 
前置通知[Before advice]:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常。 
正常返回通知[After returning advice]:在连接点正常执行完成后执行,如果连接点抛出异常,则不会执行。 
异常返回通知[After throwing advice]:在连接点抛出异常后执行。 
返回通知[After (finally) advice]:在连接点执行完成后执行,不管是正常执行完成,还是抛出异常,都会执行返回通知中的内容。 
环绕通知[Around advice]:环绕通知围绕在连接点前后,比如一个方法调用的前后。这是最强大的通知类型,能在方法调用前后自定义一些操作。环绕通知还需要负责决定是继续处理join point(调用ProceedingJoinPoint的proceed方法)还是中断执行。 
接下来通过编写示例程序来测试一下五种通知类型:

  • 定义接口
package com.chenqa.springaop.example.service;

public interface BankService { /** * 模拟的银行转账 * @param from 出账人 * @param to 入账人 * @param account 转账金额 * @return */ public boolean transfer(String form, String to, double account); }
  • 编写实现类
package com.chenqa.springaop.example.service.impl;

import com.chenqa.springaop.example.service.BankService;

public class BCMBankServiceImpl implements BankService { public boolean transfer(String form, String to, double account) { if(account<100) { throw new IllegalArgumentException("最低转账金额不能低于100元"); } System.out.println(form+"向"+to+"交行账户转账"+account+"元"); return false; } }
  • 修改spring配置文件,添加以下内容:
<!-- bankService bean -->    
    <bean id="bankService" class="com.chenqa.springaop.example.service.impl.BCMBankServiceImpl"/> <!-- 切面 --> <bean id="myAspect" class="com.chenqa.springaop.example.aspect.MyAspect"/> <!-- aop配置 --> <aop:config> <aop:aspect ref="myAspect"> <aop:pointcut expression="execution(* com.chenqa.springaop.example.service.impl.*.*(..))" id="pointcut"/> <aop:before method="before" pointcut-ref="pointcut"/> <aop:after method="after" pointcut-ref="pointcut"/> <aop:after-returning method="afterReturning" pointcut-ref="pointcut"/> <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut"/> <aop:around method="around" pointcut-ref="pointcut"/> </aop:aspect> </aop:config>
  • 编写测试程序
ApplicationContext context = new ClassPathXmlApplicationContext("spring-aop.xml");
        BankService bankService = context.getBean("bankService", BankService.class); bankService.transfer("张三", "李四", 200);

执行后输出: 

这里写图片描述 
将测试程序中的200改成50,再执行后输出: 
这里写图片描述
通过测试结果可以看出,五种通知的执行顺序为: 前置通知→环绕通知→正常返回通知/异常返回通知→返回通知,可以多次执行来查看。

 

转载于:https://www.cnblogs.com/enjoyjava/p/7828582.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值