首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring AOP XML 命名空間配置詳解(二):切面、切入點與五種通知聲明

     編輯:Java 相關知識

前言

承接上篇,本文詳細說明在 <aop:config> 中如何聲明切面、定義切入點,以及配置五種通知類型。

1. 聲明切面 <aop:aspect>

<aop:config proxy-target-class="true">
  <aop:aspect id="TestAspectName" ref="MyAspect" order="1">
    ... 切入點與通知配置 ...
  </aop:aspect>
</aop:config>
  • ref(必填):指向切面支撐 Bean (backing bean) 的 id。
  • order:切面載入順序(數值越小優先級越高)。
  • id:切面唯一標識。

2. 聲明切入點 <aop:pointcut>

<aop:pointcut id="testPointcut"
    expression="execution(* aop.test.TestBean.*(..))"/>
  • id:切入點識別碼,供通知引用。
  • expression:AspectJ 切入點運算式語法。

邏輯運算子在 XML 中的寫法:&& → and、|| → or、! → not。

引用 @Pointcut 註解定義的切入點:

<aop:pointcut id="test" expression="aop.test.MyAspect.Pointcut1()"/>

必須使用完整類別名.方法名格式。

3. 五種通知聲明

所有通知標籤共同屬性:

  • method(必填):支撐 Bean 中的通知方法名。
  • pointcut:內嵌切入點運算式。
  • pointcut-ref:引用已定義切入點 id(二擇一)。
  • arg-names:方法參數名稱對應切入點參數。

3.1 前置通知 <aop:before>

<aop:before pointcut-ref="testPointcut" method="beforeAdvice"/>

3.2 後置通知 <aop:after>

<aop:after pointcut-ref="testPointcut" method="afterAdvice"/>

3.3 返回後通知 <aop:after-returning>

<aop:after-returning pointcut-ref="testPointcut"
    method="afterReturnAdvice" returning="retVal"/>

returning 屬性將連接點返回值傳給通知方法參數 retVal。

3.4 例外通知 <aop:after-throwing>

<aop:after-throwing pointcut-ref="testPointcut"
    method="afterThrowingAdvice" throwing="ex"/>

throwing 屬性指定匹配的例外參數名。

3.5 環繞通知 <aop:around>

<aop:around pointcut-ref="testPointcut" method="aroundAdvice"/>

功能最強大,可完全控制目標方法執行(需自行呼叫 ProceedingJoinPoint.proceed())。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved