本文轉自: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,再執行后輸出: 
通過測試結果可以看出,五種通知的執行順序為: 前置通知→環繞通知→正常返回通知/異常返回通知→返回通知,可以多次執行來查看。
