使用aspectJ實現Spring AOP的兩種方式
方式一:基於aspectJ的XML配置
方式二:基於aspectJ的註解方式
基於aspectJ的XML配置
1) 引入相關jar包
2) 創建Spring核心配置文件,必須導入aop的約束
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
</beans>
3) 使用表達式配置切入點
[1] 切入點:實際增強的方法
[2] execution(<訪問修飾符>?<返回值類型><方法名全路徑>(<從參數>)<異常>)
表達式的幾種寫法:
①execution (* cn.aop.Book.add(..))對cn.aop包下的Book類中的所有方法名為add的方法進行增強
*:表示可以是任意訪問修飾符
cn.aop.Book.add:方法的全路徑
(..):表示可以有參數,也可以沒有
②execution (* cn.aop.Book.*(..))對cn.aop包下的Book類中的所有方法進行增強
③execution(* *.*(..))對所有包下的所有類中的所有方法進行增強
④execution(* save*(..))對所有以save開頭的方法進行增強
前置增強實例:
<?xml version="1.0" encoding="UTF-8"?>
|
4) 編寫測試類
public class Test {
|
測試結果如下:
後置增強實例和前置一樣
環繞增強:
需要增強的類
public class Book {
|
增強類中的方法::
public void around(ProceedingJoinPoint proceedingJoinPoint){
|
XML配置文件
<?xml version="1.0" encoding="UTF-8"?>
|
測試類
public class Test { |
執行效果
方式二: 基於aspectJ的註解方式
1) 引入相關jar包
2) 創建Spring核心配置文件,必須導入aop的約束
以上兩步驟直接參照基於aspectJ的XML配置方式
3) 在Spring配置文件中開啟aop操作
4) 在增強類上面加上@Aspectj的註解
在增強的方法上面加上@before註解 @before是前置增強
5) 創建test類,運行效果如下
使用aspectJ實現Spring AOP的兩種方式