SpringAOP表示式及五種Advice

2021-09-25 13:35:24 字數 2579 閱讀 6553

springaop表示式由三部分組成:

指示器(designators)

萬用字元(wildcards)

運算子(operators)

匹配方法:execution()

匹配註解:@target,@args,@within,@annotation

匹配包/型別:within()

匹配物件:this(),bean(),target()

匹配引數:args()

1.匹配方法:

execution表示式的格式

modidier-pattern?修飾符

ret-type-pattern 返回值

declaring-type-pattern?宣告的包名

name-pattern(param-pattern)宣告的方法名(引數名)

throws-pattern?宣告的丟擲的異常

以上帶有?的部分可以預設,其他部分則必須宣告

例如:@pointcut("execution(public * com.test.service.*service.*(..))")

表示攔截訪問控制為public ,返回值為任意型別,位於com.test.service包下任意以service結尾的類中的任意引數的任意方法。

如果想要攔截符合上述條件的某些會丟擲異常的方法則直接在表示式後加上throws 要丟擲的異常即可。

2.匹配註解:

@pointcut("@annotation(com.test.security.adminonly)")

攔截帶有com.test.security.adminonly註解的方法

@pointcut("@within(com.google.common.annotation.beta)")

攔截標註有beta的類中的方法,要求的annotation的retentionpolicy級別為class

@pointcut("@target(org.springframework.stereotype.reposity)")

攔截標註有reposity的類中的方法,要求的annotation的retentionpolicy級別為runtime

@pointcut("@args(org.springframework.stereotype.reposity)")

攔截方法中的引數的類標註有reposity註解的方法

其中@target和@within在spring context下是沒有以上的區別的

3.匹配包:

@pointcut("within(com.test.service.userservice)")

攔截com.test.service下userservice類中的所有方法

@pointcut("within(com.test.service..*)")

攔截com.test.service包及其子包下所有類的方法

4.匹配物件:

@pointcut("this(com.test.dao.userdao)")

攔截的目標物件為指定的userdao型別的方法,this攔截的是userdao的aop**物件的方法

@pointcut("target(com.test.dao.userdao)")

攔截的目標物件為指定的userdao型別的方法,target攔截的是userdao物件的方法,而不是對應的aop**物件的方法

在使用introduction動態的新增方法時,this能夠攔截到,而target攔截不到。

@pointcut("bean(*service)")

攔截所有以service結尾的bean中的方法

5.匹配引數:

@pointcut("execution(* *. . find*(long))")

攔截任何以find開頭的只有乙個long型別引數的方法

@pointcut("args(long)")

攔截任何只有乙個long引數的方法

@pointcut("execution(* *. .find*(long,..))")

攔截任何以find開頭且第乙個引數為long型別的方法

@pointcut("args(long,..)")

攔截任何第乙個引數為long型別的方法

*匹配任意的數量的字元

..匹配任意數目的子包或引數

+匹配指定類及其子類

&&邏輯與運算

||邏輯或運算

!邏輯非運算

1.@before 前置通知

2.@after 後置通知,方法執行完之後

3.@afterreturnning 返回通知,成功執行之後

4.@afterthrowing 異常通知,丟擲異常之後

5.@around 環繞通知(方法執行前後都有通知)

其中在@before通知中可以獲取攔截方法的引數值,例如:

@before(value="matchargs() && args(userid)"),可以獲取userid的值

在@afterreturnning中可以繫結返回結果,例如:

@afterreturnning(value="matchreturn() ,returnning=returnvalue"),把返回值和returnvalue繫結

Spring Aop 表示式匹配

spring aop 可以匹配多個表示式 以do開頭的方法切點 pointcut execution com.abc.action.controller.do public void dopointcut 以doselect開頭的方法切點 pointcut execution com.abc.act...

SpringAop切點表示式

1.1 springaop切點表示式 execution 訪問修飾符 返回值型別 包名.類名.方法名 引數 execution public void com.zhan.aop.target.method 返回值型別 包名 類名 方法名可以用 代表任意 包名與類名之間有個.代表當前包下的類,兩個點....

Spring AOP程式設計增強表示式

1.spring中通過切入點表示式定義具體切入點 指示符作用bean 用於匹配指定包名下型別內的方法執行 within 用於匹配指定包名下型別內的方法執行 execution 用於進行細粒度方法匹配執行具體業務 annotation 用於匹配指定註解修飾的方法執行 1.1 bean表示式應用於類級別...