AOP 近年風靡,Spring、JAC、JBoss AOP 等框架層出不窮。本文不依賴任何第三方框架,僅用 JDK 內建動態代理,以最簡單範例展示 AOP 核心運作原理,適合初學者快速入門。
典型應用場景:日誌記錄、效能統計、安全控制、事務處理。目標是將這些橫切行為從業務類別中剝離,獨立配置、獨立演進,不影響業務核心代碼。
public class BusinessObject implements BusinessInterface {
private Logger logger = Logger.getLogger(this.getClass().getName());
public void processBusiness() {
try {
logger.info("start to processing...");
// business logic here
System.out.println("here is business logic");
logger.info("end processing...");
} catch (Exception e) {
logger.info("exception happens...");
}
}
}
缺點:日誌代碼散落於每個業務方法、維護困難、大量重複代碼。
public interface BusinessInterface {
void processBusiness();
}
public class BusinessObject implements BusinessInterface {
public void processBusiness() {
System.out.println("here is business logic");
}
}
import java.lang.reflect.*;
public class LogHandler implements InvocationHandler {
private Logger logger = Logger.getLogger(this.getClass().getName());
private Object delegate;
public LogHandler(Object delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
logger.info("method starts... " + method);
result = method.invoke(delegate, args);
logger.info("method ends... " + method);
} catch (Exception e) {
logger.info("Exception happens... " + e);
}
return result;
}
}
BusinessInterface businessImpl = new BusinessObject();
InvocationHandler handler = new LogHandler(businessImpl);
BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(
businessImpl.getClass().getClassLoader(),
businessImpl.getClass().getInterfaces(),
handler
);
proxy.processBusiness();
INFO: method starts... processBusiness
here is business logic
INFO: method ends... processBusiness
Proxy.newProxyInstance 依介面動態生成代理類別,實作 InvocationHandler。invoke(),攔截器可在前後織入邏輯。LogHandler,複用性極佳。JDK 動態代理僅支援介面代理,且單一代理實例僅能綁定一個 InvocationHandler。若需同時套用日誌、效能、事務等多重攔截,需自行實作 Handler 鏈或採用 CGLIB/ASM 等類別級代理庫。生產環境強烈建議直接使用 Spring AOP,已完整解決多重通知鏈、切點表達式、事務整合等工程化問題。
動態代理是 AOP 最基礎的實作技術之一。理解其運作原理,有助於深入掌握 Spring AOP 等主流框架的底層邏輯,並在框架無法滿足特殊需求時,具備自行擴充的能力。