傳統業務代碼中,日志、事務、權限等「橫切關注點」散落在每個方法裡,導致:
AOP 將這些通用功能抽取為「切面」,由容器動態織入目標方法,實現關注點分離。
LoggingAspect、TxAspect、AuthAspect。配置中聲明為切面。execution(* com.service.*.*(..))。// 簡化版 JDK 動態代理示意
public class AopProxy implements InvocationHandler {
private Object target;
private List advices;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 1. 執行前置通知
for (Advice a : advices) if (a instanceof BeforeAdvice) a.before(method, args);
try {
// 2. 調用目標方法
Object result = method.invoke(target, args);
// 3. 執行後置通知
for (Advice a : advices) if (a instanceof AfterReturningAdvice) a.afterReturning(result);
return result;
} catch (Exception e) {
// 4. 執行異常通知
for (Advice a : advices) if (a instanceof ThrowsAdvice) a.afterThrowing(e);
throw e;
} finally {
// 5. 執行最終通知
for (Advice a : advices) if (a instanceof AfterAdvice) a.after();
}
}
}
| 維度 | OOP | AOP |
|---|---|---|
| 關注點 | 業務實體及其屬性/行為 | 業務流程中的步驟/階段 |
| 封裝粒度 | 類/對象 | 方法/切面 |
| 復用方式 | 繼承/組合 | 動態織入/代理 |
| 耦合度 | 業務邏輯內聚 | 橫切邏輯解耦 |
| 典型場景 | 領域建模 | 日志、事務、安全、緩存、監控 |
最佳實踐:OOP 構建領域模型骨架,AOP 處理橫切關注點,二者結合實現高內聚低耦合。
// 1. 定義切面
@Aspect
@Component
public class LogAspect {
@Pointcut("execution(* com.service..*(..))")
public void serviceLayer() {}
@Before("serviceLayer()")
public void logBefore(JoinPoint jp) { /* ... */ }
@Around("serviceLayer()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object ret = pjp.proceed();
System.out.println(pjp.getSignature() + " 耗時 " + (System.currentTimeMillis()-start) + "ms");
return ret;
}
}
// 2. 啟用
@EnableAspectJAutoProxy
@Configuration
public class AopConfig {}
JS 無靜態類型與註解,但憑藉動態語言特性(函數為一等公民、原型鏈、閉包)可輕鬆實現:
fn = fn.before(beforeFn).after(afterFn)Object.keys(obj).forEach(k => { if (typeof obj[k]==='function') obj[k]=advice(obj[k]); })new Proxy(target, { apply: (t, ctx, args) => { /* before */ var r=t.apply(ctx,args); /* after */ return r; } })AOP 不是銀彈,但對於「散落、重複、與業務無關」的橫切邏輯,它是降低耦合、提升維護性的利器。理解七大核心概念與織入原理,能幫助你在任何語言、任何框架中識別並應用 AOP 思想。