spring aop 的五种通知类型

2023-03-14,,

本文转自: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,再执行后输出: 

通过测试结果可以看出,五种通知的执行顺序为: 前置通知→环绕通知→正常返回通知/异常返回通知→返回通知,可以多次执行来查看。

spring aop 的五种通知类型的相关教程结束。

《spring aop 的五种通知类型.doc》

下载本文的Word格式文档,以方便收藏与打印。