1. 程式人生 > >Spring AOP前置通知和後置通知

Spring AOP前置通知和後置通知


在Spring中啟用AspectJ註解支援
  要在Spring應用中使用AspectJ註解,必須在classpath下包含AspectJ類庫:aopalliance.jar、aspectj.weaver.jar和spring-aspects.jar
  將aop Schema新增到<beans>根元素中。
  要在Spring IOC容器中啟用AspectJ註解支援,只要早bean配置檔案中定義一個空的XML元素<aop:aspectj-autoproxy>
  當Spring IOC容器偵測到bean配置檔案中的<aop:aspectj-autoproxy>元素時,會自動為與AspectJ切面匹配的bean建立代理


用AspectJ註解宣告切面
  要在Spring中宣告AspectJ切面,只需要在IOC容器中將切面宣告為bean例項。當在Spring IOC容器中初始化AspectJ切面之後,Spring IOC容器就會為那些與AspectJ切面相匹配的bean建立代理
  在AspectJ註解中,切面只是一個帶有@AspectJ註解的Java類
  通知是標註有某種註解的簡單的Java方法
  AspectJ支援5種類型的通知註解:
    @Before:前置通知,在方法執行之前返回
    @After:後置通知,在方法執行後執行
    @AfterRunning:返回通知,在方法返回結果之後執行
    @AfterThrowing:異常通知,在方法丟擲異常之後
    @Around:環繞通知,圍繞著方法執行

利用方法簽名編寫AspectJ切入點表示式
  最典型的切入點表示式時根據方法的簽名來匹配各種方法:
    -execution * com.yl.spring.aop.ArithmeticCalculator.*(..):匹配ArithmeticCalculator中宣告的所有方法,第一個*代表任意修飾符及任意返回值,第二個*代表任意方法,..匹配任意數量的引數。若目標類與介面與切面在同一個包中,可以省略包名。
    -execution public * ArithmeticCalculator.*(..):匹配ArithmeticCalculator介面的所有公有方法
    -execution public double ArithmeticCalculator.*(..):匹配ArithmeticCalculator中返回double型別數值的方法
    -execution public double ArithmeticCalculator.*(double, ..):匹配第一個引數為double型別的方法,..匹配任意數量任意型別的引數
    -execution public double ArithmeticCalculator.*(double, double):匹配引數型別為double,double型別的方法

後置通知
  後置通知是在連線點完成之後執行的,即連線點返回結果或者丟擲異常的時候,下面的後置通知記錄了方法的終止。
  一個切面可以包括一個或者多個通知