spring aop 五大通知類型


1、定義

1、before(前置通知):在連接點方法之前執行,不能控制連接點方法是否執行。

2、after(后置通知):又名最終通知,連接點方法只要執行,不管會不會出現錯誤,它最后都會被執行。

3、after-return(返回通知):連接點正常執行,並且不會報錯才會執行。

4、throwing(異常通知):連接點方法拋出異常時才會執行,這個通知不能處理異常,只能得到異常信息,異常通知如果想要把目標方法拋出的異常傳遞給通知方法,只要在異常通知的throwing屬性設置等於通知方法的參數名即可。 如果沒有設置異常類型,目標方法拋出任何異常,此通知不執行,后面的通知都會執行。 有設置異常類型做參數,目標方法拋出的異常是通知方法參數的指定類型異常或子類型時,此通知方法才會得到執行。

5、around(環繞通知):結合了上面四種通知,加強版的通知,可以實現上面四種通知的功能。

2、before(前置通知)

after和after-return和前置通知差不多,就不做解釋了。

普通前置通知

<aop:before method="BeforeInsert" pointcut-ref="studentPointcut"/>
//通知方法
public
void BeforeInsert(JoinPoint joinPoint){ System.out.println(joinPoint); System.out.println("BeforeInsert as LogImpl"); }

通知方法可以選擇是否帶參數,可帶JoinPoint參數,這個參數包含了連接點的一些信息。

我們也可以在這里獲取連接點方法的參數值。

連接點

public int add(int num1,int num2){
    return num1+num2;
}

通知

public void beforeInsert(JoinPoint joinPoint,int n,int m){
    System.out.println(n);
    System.out.println(m);
    System.out.println(joinPoint);
    System.out.println("BeforeInsert as LogImpl");
}

xml

<aop:config>
    <!--切點表達式中添加and 設置別名,可以設置和通知方法的參數名一樣的-->
        <aop:pointcut id="studentPointcut" expression="execution(* com.target.StudentDaoImpl.*(..)) and args(n,m)"/>
        <aop:aspect id="logAspect" ref="log">
            <!--arg-names對應切點表達式的別名-->
            <aop:before method="beforeInsert" pointcut-ref="studentPointcut" arg-names="n,m"/>
        </aop:aspect>
</aop:config>

切點表達式設置了args(n,m),那么其它通知也需要添加對應的方法參數和設置arg-names

3、throwing(異常通知)

<aop:after-throwing method="throwInsert" pointcut-ref="studentPointcut" throwing="ey"/>

throwing指定異常類型參數

public void throwInsert(RuntimeException ey) {
    System.out.println("throwException");
}

如果異常通知方法沒有設置異常參數,throwing不用設置參數,目標方法產生的所有異常都會使用此通知方法

異常通知方法設置了異常參數,throwing需要設置跟異常參數,目標方法產生的異常是此通知異常類型或子類型時,該通知方法才會被使用。

4、around(環繞通知)

<aop:around method="aroundInsert" pointcut-ref="studentPointcut"/>

通知方法:

public Object aroundInsert(ProceedingJoinPoint joinPoint){
    //相當於before
    System.out.println("Before....");
    //定義result保存調用方法結果
    Object result = null;
    try {
        //調用方法
        result = joinPoint.proceed();
        //相當於after-return
        System.out.println("after-return....");
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        //相當於throwing
        System.out.println("throwing....");
    }
    //相當於after
    System.out.println("after....");
    //返回結果
    return result;
}

around一般使用比較多,因為它包含了上面四種的功能。

ProceedingJoinPoint 一般作為環繞通知方法的參數,它實現了JoinPoint接口,增強版。可以控制目標方法的執行

以及查看目標方法的參數等等。

JoinPoint作為上面四種通知的參數。它包含了一系列的目標方法的信息。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM