spring aop的五种通知类型
来源:互联网 发布:查询身份证归属地软件 编辑:程序博客网 时间:2024/05/11 16:48
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,再执行后输出:
通过测试结果可以看出,五种通知的执行顺序为: 前置通知→环绕通知→正常返回通知/异常返回通知→返回通知,可以多次执行来查看。
0 0
- spring aop的五种通知类型
- spring aop的五种通知类型
- spring aop的五种通知类型
- spring aop的五种通知类型
- spring aop的五种通知类型(基于XML)
- Spring - 注解实现AOP的五种通知
- Spring AOP实例(五大通知类型)
- spring aop五种通知及通知中传递参数!
- AOP的通知类型
- Spring的AOP通知
- Spring 的几种AOP通知
- Spring AOP四种创建通知(拦截器)类型实例
- Spring AOP四种创建通知(拦截器)类型实例
- Spring AOP四种创建通知(拦截器)类型实例
- Spring AOP四种创建通知(拦截器)类型实例
- Spring AOP四种创建通知(拦截器)类型实例
- spring知识六------AOP五大通知
- Spring容器切面编程 aop注解开发 五中通知类型
- 接口的定义与实现
- B-tree和B+tree浅析
- DB2恢复( RESTORE&ROLLFORWARD)
- 关于wifi的方法
- UITableViewCell 代码实现高度动态,根据服务器传输过来的数据
- spring aop的五种通知类型
- hdu 5285 wyh2000 and pupil 二分图染色发判定,求最大匹配
- 杭电oj1001题 a+b
- Oracle 中文乱码问题
- EasyUI——DataGrid中嵌入Radio
- 常用的Bash快捷键
- [C++设计模式] adapter 适配器模式
- Android surfaceView(一)
- JAVA常用类之——Math和Random