AOP場景
AOP: Aspect Oriented Programming (面向切面編程)
OOP: Object Oriented Programming (面向對象編程)
場景設計
- 設計: 編寫一個計算器接口和實現類,提供加減乘除四則運算
- 需求: 在加減乘除運算的時候需要記錄操作日志(運算前參數、運算后結果)
- 實現方案:
- 硬編碼
- 靜態代理
- 動態代理
- AOP
硬編碼
使用硬編碼的方式記錄日志
- 創建工程環境: 新建模塊, 加一個lombok依賴
- 新建計算器接口和實現類, 并在實現類中, 通過硬編碼記錄日志
package com.guigu.aop.calculator;// 定義四則運算
public interface MathCalculator {// 加法int add(int i, int b);// 減法int sub(int i, int b);// 乘法int mul(int i , int b);// 除法int div(int i, int b);
}
package com.guigu.aop.calculator.impl;/*** 計算器實現類* 1. 硬編碼: 不推薦; 耦合:(通用邏輯 + 專用邏輯)希望不要耦合; 耦合太多就是維護地獄*/
@Component
public class MathCalculatorImpl implements MathCalculator {@Overridepublic int add(int i, int b) {System.out.println("[日志] add開始, 參數:" + i + "," + b);int res = i + b;System.out.println("[日志] add結束, 結果:" + res);return res;}@Overridepublic int sub(int i, int b) {return i -b;}@Overridepublic int mul(int i, int b) {return i * b;}@Overridepublic int div(int i, int b) {return i / b;}
}
- 新建單元測試, 測試一下
package com.guigu.aop;@SpringBootTest
public class MathTest {@AutowiredMathCalculatorImpl mathCalculator;@Testvoid test01() {int add = mathCalculator.add(1, 9);}
}
靜態代理
編碼時介入: 包裝真實對象,對外提供靜態代理對象
實現步驟
- 包裝被代理對象
- 實現被代理對象的接口
- 運行時調用被代理對象的真實方法
- 外部使用代理對象調用
優點
- 實現簡單
缺點
- 需要為不同類型編寫不同代理類,導致擴展維護性差
使用靜態代理技術, 記錄代碼日志
package com.guigu.aop.proxy.statics;import com.guigu.aop.calculator.MathCalculator;
import lombok.Data;
import org.springframework.stereotype.Component;/*** 靜態代理: 定義代理對象, 幫助目標對象完成一些工作*/
@Component
@Data
public class CalculatorStaticProxy implements MathCalculator {private MathCalculator target; // 目標對象public CalculatorStaticProxy(MathCalculator mc) {this.target = mc;}@Overridepublic int add(int i, int b) {System.out.println("[日志] add開始, 參數:" + i + "," + b);int res = target.add(i, b);System.out.println("[日志] add結束, 結果:" + res);return res;}@Overridepublic int sub(int i, int b) {return target.sub(i, b);}@Overridepublic int mul(int i, int b) {return target.mul(i, b);}@Overridepublic int div(int i, int b) {return target.div(i, b);}
}
package com.guigu.aop;@SpringBootTest
public class MathTest {@AutowiredCalculatorStaticProxy calculatorStaticProxy;@Testvoid test02() {int add = calculatorStaticProxy.add(2, 3);}
}
動態代理
運行時介入: 創建真實對象運行時代理對象
- 實現步驟
- ·Java 反射提供 Proxy.newProxyInstance 的方式創建代理對象
- 優點:
- 節約不同代理類的開發
- 缺點:
- 開發難度大
- 必須有接口,才能創建動態代理
使用動態代理技術, 記錄代碼日志
- 封裝一個日志工具類, 提供記錄日志的靜態方法
package com.guigu.aop.log;public class LogUtils {public static void logStart(String name, Object... args) {System.out.println("[日志]: [" + name + "]開始, 參數:" + Arrays.toString(args));}public static void logEnd(String name) {System.out.println("[日志]: [" + name + "]結束");}public static void logException(String name, Throwable e) {System.out.println("[日志]: [" +name+ "]異常: 異常信息:" + e.getCause());}public static void logReturn(String name, Object result) {System.out.println("[日志]: [" + name + "]結束, 返回結果:" + result);}
}
- 創建動態代理類 封裝一個靜態方法, 可以傳入任何對象, 返回代理對象
package com.guigu.aop.proxy.dynamic;/*** 動態代理* 1.是java原生支持的技術* 2.運行期間才決定代理關系, 類似于攔截器的思想* 3.目標對象在執行期間會被動態攔截, 可以插入指定邏輯* 4.優點: 可以代理任何對象* 5.缺點: 代碼多* 6.強制要求: 目標對象必須有接口(否則報錯), 代理的也只是接口規定的方法,*/
@Component
public class DynamicProxy {// 獲取目標對象的代理對象public static Object getProxyInstance(Object target) {/*** Proxy是java反射包提供的類* 下面的方法可以創建對象的代理對象, 需要三個參數* Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)* 參數1: ClassLoader loader, 類加載器 (通過類加載器拿到目標對象)* 參數2: Class<?>[] interfaces, 目標對象實現的接口 (通過接口拿到目標對象實現的方法)* 參數3: InvocationHandler h, 代理對象需要執行的方法, 這個方法中可以插入指定邏輯*//*** 攔截方法說明:* 通過攔截方法, 可以攔截到目標對象方法的調用, 從而做任何事情* (proxy, method, args)-> { }* proxy: 代理對象* method: 準備執行的目標對象的方法* args: 方法調用傳遞的參數*/return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),(proxy, method, args)-> {String name = method.getName();// 記錄開始LogUtils.logStart(name, args);Object result = null;try {result = method.invoke(target, args); // 執行目標對象的方法// 記錄返回值LogUtils.logReturn(name, result);} catch (Exception e) {// 記錄異常LogUtils.logException(name, e);} finally {// 記錄結束LogUtils.logEnd(name);}return result;});}
}
- 使用動態代理類的方法創建代理對象
package com.guigu.aop;@SpringBootTest
public class MathTest {@AutowiredMathCalculatorImpl mathCalculator;@AutowiredDynamicProxy dynamicProxy;@Testvoid test03() {MathCalculator instance =( MathCalculator) dynamicProxy.getProxyInstance(mathCalculator);instance.add(3,5);}
}
AOP使用
了解AOP的術語
AOP基本使用步驟
- 導入AOP依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
- 編寫切面Aspect
package com.guigu.aop.aspect;@Component
@Aspect // 告訴spring這個組件是一個切面
public class LogAspect {}
- 編寫通知方法
package com.guigu.aop.aspect;@Component
@Aspect // 告訴spring這個組件是一個切面
public class LogAspect {public void logStart() {System.out.println("[切面-日志]開始...");}public void logEnd() {System.out.println("[切面-日志]結束...");}public void logReturn() {System.out.println("[切面-日志]返回結果");}public void logException() {System.out.println("[切面-日志]爬出拋出異常:");}
}
- 指定切入點表達式
package com.guigu.aop.aspect;import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;@Component
@Aspect // 告訴spring這個組件是一個切面
public class LogAspect {/*** 告訴Spring, 以下通知何時何地生效?* 何時?* 通知方法:* @Before: 方法執行前運行* @AfterReturning: 方法執行正常返回結果運行* @AfterThrowing: 方法拋出異常時運行* @After: 方法執行之后運行* 何地:* 切入點表達式:* 1. execution(方法的全簽名)* 作用: 根據方法匹配切入點* 全寫法: [public] int [com.guigu.aop.calculator].add(int, int) [throws ArithmeticException]* 省略寫法: int add(int, int)* 通配符:* *: 表示任意字符* ..: 表示多個參數, 任意類型* 最省略: * *(..)*/@Before("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void logStart() {System.out.println("[切面-日志]開始...");}@After("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void logEnd() {System.out.println("[切面-日志]結束...");}@AfterReturning("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void logReturn() {System.out.println("[切面-日志]返回結果");}@AfterThrowing("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void logException() {System.out.println("[切面-日志]爬出拋出異常:");}
}
- 測試AOP動態織入
package com.guigu.aop;import com.guigu.aop.calculator.MathCalculator;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class AopTest {@Autowired // 容器中注入的是 MathCalculator 的代理對象MathCalculator mathCalculator;@Testvoid test01() {System.out.println(mathCalculator.getClass()); // 看看代理對象mathCalculator.add(10, 20);}
}
AOP細節
切入點表達式
切入點表達式的寫法
package com.guigu.aop.annotation;import java.lang.annotation.*;// 自定義接口
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAn {
}
package com.guigu.aop.calculator.impl;import com.guigu.aop.annotation.MyAn;
import com.guigu.aop.calculator.MathCalculator;
import org.springframework.stereotype.Component;/*** 計算器實現類* 1. 硬編碼: 不推薦; 耦合:(通用邏輯 + 專用邏輯)希望不要耦合; 耦合太多就是維護地獄*/
@Component
public class MathCalculatorImpl implements MathCalculator {@Overridepublic int add(int i, int b) {int res = i + b;return res;}@Overridepublic int sub(int i, int b) {return i -b;}@Overridepublic int mul(int i, int b) {return i * b;}@MyAn@Overridepublic int div(int i, int b) {return i / b;}
}
package com.guigu.aop.aspect;import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;@Component
@Aspect // 告訴spring這個組件是一個切面
public class LogAspect {/*** 告訴Spring, 以下通知何時何地生效?* 何時?* @Before: 方法執行前運行* @AfterReturning: 方法執行正常返回結果運行* @AfterThrowing: 方法拋出異常時運行* @After: 方法執行之后運行* 何地:* 切入點表達式:* 1. execution(方法的全簽名)* 作用: 根據方法匹配切入點* 全寫法: [public] int [com.guigu.aop.calculator].add(int, int) [throws ArithmeticException]* 省略寫法: int add(int, int)* 通配符:* *: 表示任意字符* ..: 表示多個參數, 任意類型* 最省略: * *(..)* 2. args(參數類型或其子類型)* 作用: 根據方法的參數匹配切入點* 3. annotation(注解類型)* 作用: 根據方法的注解匹配切入點, 一般配合自定義注解使用*/@Before("args(int, int)")public void logHaha() {System.out.println("[切面-日志]哈哈...");}@Before("@annotation(com.guigu.aop.annotation.MyAn)")public void logHehe() {System.out.println("[切面-日志]呵呵...");}
}
package com.guigu.aop;@SpringBootTest
public class AopTest {@Autowired // 容器中注入的是 MathCalculator 的代理對象MathCalculator mathCalculator;@Testvoid test02() {// 根據方法的參數匹配切入點mathCalculator.add(1, 2);// 測試方法的注解匹配切入點mathCalculator.div(1, 2);}
}
執行順序
AOP 的底層原理
1、Spring會為每個被切面切入的組件創建代理對象(Spring CGLIB 創建的代理對象,無視接口)。
2、代理對象中保存了切面類里面所有通知方法構成的增強器鏈。
3、目標方法執行時,會先去執行增強器鏈中拿到需要提前執行的通知方法去執行
通知方法的執行順序
- 正常鏈路: 前置通知->目標方法->返回通知->后置通知
- 異常鏈路: 前置通知->目標方法->異常通知->后置通知
連接點信息
通過 JoinPoint 包裝了當前目標方法的所有信息
通過 returning 屬性可以接收當前方法的返回值
通過 throwing 屬性可以接收當前方法的異常信息
package com.guigu.aop.aspect;@Component
@Aspect // 告訴spring這個組件是一個切面
public class LogAspect {@Before("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void logStart(JoinPoint joinPoint) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();// 獲取方法的參數值Object[] args = joinPoint.getArgs();System.out.println("【切面- 日志】【" + name + "】開始:參數列表:【" + Arrays.toString(args) + "】");}@After("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void logEnd(JoinPoint joinPoint) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("[切面-日志] " + name + "結束...");}@AfterReturning(value = "execution(int com.guigu.aop.calculator.MathCalculator.*(..))",returning = "result")public void logReturn(JoinPoint joinPoint, Object result) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("【切面 -日志】【" + name + "】返回:值:" + result);}@AfterThrowing(value = "execution(int com.guigu.aop.calculator.MathCalculator.*(..))",throwing = "e")public void logException(JoinPoint joinPoint, Exception e) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("【切面 - 日志】【" + name + "】異常:錯誤信息:【" + e.getMessage() + "】");}}
抽取切入點表達式
使用@Pointcut 注解抽取切入點表達式
package com.guigu.aop.aspect;@Component
@Aspect // 告訴spring這個組件是一個切面
public class LogAspect {@Pointcut("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void pointCut(){};@Before("pointCut()")public void logStart(JoinPoint joinPoint) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();// 獲取方法的參數值Object[] args = joinPoint.getArgs();System.out.println("【切面- 日志】【" + name + "】開始:參數列表:【" + Arrays.toString(args) + "】");}@After("pointCut()")public void logEnd(JoinPoint joinPoint) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("[切面-日志] " + name + "結束...");}@AfterReturning(value = "pointCut()",returning = "result")public void logReturn(JoinPoint joinPoint, Object result) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("【切面 -日志】【" + name + "】返回:值:" + result);}@AfterThrowing(value = "pointCut()",throwing = "e")public void logException(JoinPoint joinPoint, Exception e) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("【切面 - 日志】【" + name + "】異常:錯誤信息:【" + e.getMessage() + "】");}}
多切面的執行順序
默認情況下, 切面方法的執行順序受切面類的首字母排序影響
通過 Order 注解可以指定切面類的優先級
package com.guigu.aop.aspect;@Order(1) // 數值越小, 優先級越高, 執行越早
@Component
@Aspect
public class LogAspect {@Pointcut("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void pointCut(){};@Before("pointCut()")public void logStart(JoinPoint joinPoint) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();// 獲取方法的參數值Object[] args = joinPoint.getArgs();System.out.println("【切面- 日志】【" + name + "】開始:參數列表:【" + Arrays.toString(args) + "】");}@After("pointCut()")public void logEnd(JoinPoint joinPoint) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("[切面-日志] " + name + "結束...");}@AfterReturning(value = "pointCut()",returning = "result")public void logReturn(JoinPoint joinPoint, Object result) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("【切面 -日志】【" + name + "】返回:值:" + result);}@AfterThrowing(value = "pointCut()",throwing = "e")public void logException(JoinPoint joinPoint, Exception e) {// 拿到方法全簽名MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 獲取方法名String name = signature.getName();System.out.println("【切面 - 日志】【" + name + "】異常:錯誤信息:【" + e.getMessage() + "】");}
}
package com.guigu.aop.aspect;@Component
@Aspect
public class AuthAspect {@Pointcut("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void pointCut(){};@Before("pointCut()")public void authStart() {System.out.println("[切面-權限] 開始");}@After("pointCut()")public void authEnd() {System.out.println("[切面-權限] 結束");}@AfterReturning("pointCut()")public void authReturn() {System.out.println("【切面 -權限】 返回");}@AfterThrowing("pointCut()")public void authException() {System.out.println("【切面 - 權限】 異常");}}
package com.guigu.aop;@SpringBootTest
public class AopTest {@Testvoid test04() {mathCalculator.add(1, 2);}
}
環繞通知
環繞通知可以控制目標方法是否執行, 修改目標方法的參數和執行結果
package com.guigu.aop.aspect;@Aspect
@Component
public class AroundAspect {/*** 環繞通知的固定寫法如下* Object: 返回值* ProceedingJoinPoint: 可以繼續推進的切入點*/@Pointcut("execution(int com.guigu.aop.calculator.MathCalculator.*(..))")public void pointCut(){};@Around("pointCut()")public Object around(ProceedingJoinPoint pjp) throws Throwable {// 獲取目標方法的參數Object[] args = pjp.getArgs();System.out.println("[切面-環繞前置]: 參數" + Arrays.toString(args));Object proceed = null;try {// 繼續執行目標方法proceed = pjp.proceed(args);System.out.println("[切面-環繞返回]: 返回值" + proceed);} catch (Throwable e) {System.out.println("[切面-環繞異常]: 異常信息" + e.getMessage());throw e; // 拋出異常, 讓別人繼續感知, 否則異常會被吃掉, 影響后面的程序} finally {System.out.println("[切面-環繞后置]");}// 目標方法執行完畢,返回結果return proceed;}
}
package com.guigu.aop;@SpringBootTest
public class AopTest {@Autowired // 容器中注入的是 MathCalculator 的代理對象MathCalculator mathCalculator;@Testvoid test04() {mathCalculator.add(1, 2);}
}