AspectJ中的五種增強註解及其詳解

2021-09-25 08:04:20 字數 3473 閱讀 1096

1、新增jar類庫

2.在spring配置檔案中新增如下**

第一行是掃瞄自定義的包,這次所有與測試相關的類都在com.jd中

第二行是建立乙個自定義的類的bean放在ioc容器中

第三行解釋:如果建立目標物件的目標類中的方法與aspectj切面中切入點表示式匹配,則自動為該目標物件生成動態**物件,該**物件預設使用jdk動態**,即proxy-target-class="false",當為true時為cglib**。

3.此次測試**

①.calculatoraspect類(設定增強方法)

@aspect

@component

public class calculatoraspect

@before("pointcut()")

public void before(joinpoint joinpoint)

@afterreturning(value="pointcut()",returning="result")

public void afterreturning(joinpoint joinpoint,object result)

@after("pointcut()")

public void after(joinpoint joinpoint)

@afterthrowing(value="pointcut()",throwing="excption")

public void afterthrowing(joinpoint joinpoint,exception excption)

}

②.calculatorservice類

@component

public class calculatorservice implements icalculatorservice

@override

public int div(int a, int b)

}

③.icalculatorservice介面

public inte***ce icalculatorservice
④.test類

public class test 

}

4.分析增強的執行過程

執行test類中的main方法發現執行結果如下

我們故意設定乙個錯誤(在service類中)

@override

public int div(int a, int b)

return result;

}

執行結果如下

我們將println的輸出與增強方法一一對應,我們會發現增強方法的執行過程是加有@before註解的方法-->執行增強的目標方法-->@after註解所修飾的方法-->@afterreturning註解所修飾的方法-->@afterthrowing註解所修飾的方法

實際上這些方法是這樣執行的

aspectj一共支援5種型別的增強註解,除了@before,@after,@afterreturning和@afterthrowing以外,還有一種增強註解——@around,在@around修飾的方法中可以實現@before,@after,@afterreturning和@afterthrowing增強效果,可以實現動態**全過程,**如下:

@aspect

@component

public class calculatoraspect

@around("pointcut()")

public object around(proceedingjoinpoint joinpoint) finally

//返回增強

system.out.println(object.getclass().getname()+":result of the "+name+" method:"+result);

} catch (throwable e)

return result; }

}

結果如下

與上面執行結果相同,因此可得出乙個結論@around註解的方法可以代替其他四種增強方法

注意:如果 @afterthrowing所註解的方法中異常的型別若與方法中丟擲的異常型別不匹配會怎樣呢?

相應的方法修改如下

@override

public int div(int a, int b)

return result;

}

@afterthrowing(value="pointcut()",throwing="excption")

public void afterthrowing(joinpoint joinpoint,nullpointerexception excption)

執行結果如下

也就是說@afterthrowing註解的方法並沒有起作用

使用最先提到的四種註解與@around註解的區別

1.@before、@after、@afterrunning和@afterthrowing修飾的方法可以通過宣告joinpoint 型別引數變數獲取目標方法的資訊;@around修飾的方法必須宣告proceedingjoinpoint型別的引數獲取目標方法的資訊

2.@before、@after、@afterrunning和@afterthrowing修飾的方法沒有返回值;而@around修飾的方法必須有返回值,返回值為目標方法的返回值

AOP操作AspectJ註解實現增強功能

先在xml檔案裡配置上aop和context,用context來開啟註解掃瞄,aop生成增強物件 開啟註解掃瞄 package cn.zsp.spring5.aopnno context component scan 開啟aspect生成增強物件 aop aspectj autoproxy bean...

AspectJ基於註解的AOP 實現

配置檔案 demo aspect public class myaspect signature signature joinpoint.getsignature system.out.println 方法的定義簽名signature signature string name joinpoint....

AspectJ的兩種實現

基於xml方式實現 public class myaspect public void myafterretruning joinpoint joinpoint public inte ce userservice 1.建立實體類 userserviceid class com.itt.c aspe...