AOP詳解 實現步驟

2021-10-11 17:42:35 字數 2035 閱讀 7320

在軟體業,aop為aspect oriented programming的縮寫,意為:面向切面程式設計,通過預編譯方式和執行期間動態**實現程式功能的統一維護的一種技術。aop是oop的延續,是軟體開發中的乙個熱點,也是spring框架中的乙個重要內容,是函式式程式設計的一種衍生范型。利用aop可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。

aop公式:

aop(切面)=通知方法(5種)+切入點表示式(4種)

通知方法:

1.before通知 在執行目標方法之前執行

2.afterreturning 通知 在目標方法執行之後執行

3.afterthrowing 通知 在目標方法執行之後報錯時執行

4.after 通知 無論什麼時候程式執行完成都要執行的通知

上述的4大通知型別,不能控制目標方法是否執行.一般用來***記錄程式***的執行的狀態.

一般應用與監控的操作.

5.around通知(功能最為強大的) 在目標方法執行前後執行.

因為環繞通知可以控制目標方法是否執行.控制程式的執行的軌跡.

連線點問題:joinpoint 與 proceedingjoinpoint

joinpoint能用在這五種通知方法中,proceedingjoinpoint只能用在環繞通知中!

proceedingjoinpoint中有乙個核心方法proceed方法,這個方法控制目標方法執行,因為五大通知中只有around可以控制目標方法是否執行。

切入點表示式

1.bean(「bean的id」) 粒度: 粗粒度 按bean匹配 當前bean中的方法都會執行通知.

2.within(「包名.類名」) 粒度: 粗粒度 可以匹配多個類

3.execution(「返回值型別 包名.類名.方法名(引數列表)」) 粒度: 細粒度 方法引數級別

4.@annotation(「包名.類名」) 粒度:細粒度 按照註解匹配

1.@pointcut(「bean(itemserviceimpl)」)

2.@pointcut(「within(com.jt.service.itemserviceimpl)」)

3.@pointcut(「within(com.jt.*)」) // .*一級包路徑 ,..*所有子孫後代包

4.@pointcut(「execution(* com.jt.service..*.*(..))」)

//注釋: 返回值型別任意型別 在com.jt.service下的所有子孫類 以add開頭的方法,任意引數型別

例:

//@pointcut("bean(itemcatserviceimpl)")

//@pointcut("within(com.jt.service.itemcatserviceimpl)")

//@pointcut("within(com.jt.service.*)") // .* 一級包路徑 ..* 所有子孫後代包

//@pointcut("execution(返回值型別 包名.類名.方法名(引數列表))")

@pointcut("execution(* com.jt.service..*.*(..))")

//注釋: 返回值型別任意型別 在com.jt.service下的所有子孫類 以add開頭的方法,任意引數型別

public void pointcut()

/** * 需求:

* 1.獲取目標方法的路徑

* 2.獲取目標方法的引數.

* 3.獲取目標方法的名稱

*/@before("pointcut()")

public void before(joinpoint joinpoint)

@around("pointcut()")

public object around(proceedingjoinpoint joinpoint) catch (throwable throwable)

}

spring實現aop的步驟

首先注意匯入乙個jar包!component spring要管理的話需要把這個類註解成容器 aspect 切面類 public class logaspect 定義通知 解釋 切點之前的通知 前置通知 before pointcut public void dobefore joinpoint jo...

AOP概念詳解

aop aspect oriented programming 面向切面思想,是spring的三大核心思想之一 兩外兩個 ioc 控制反轉 di 依賴注入 程式中一般都存在一些系統性的去求,許可權校驗 日誌記錄 統計等。有多少業務操作,就要寫多少重複的校驗和日誌記錄 運用物件導向的思想,我們可以把這...

Spring中AOP開發步驟

aop 不是由spring定義.aop聯盟的組織定義.spring中的通知 增強 前置通知 org.springframework.aop.methodbeforeadvice 在目標方法執行前實施增強 後置通知 org.springframework.aop.afterreturningadvic...