AOP 近年風靡,Spring、JAC、JBoss AOP 等框架百家爭鳴。本文不談理論,透過簡單範例示範如何利用 JDK 內建動態代理實作 AOP,將日誌記錄、效能統計等橫切關注點從業務邏輯中分離。
public void processBusiness() {
logger.info("start...");
// business logic
logger.info("end...");
}
每個 BusinessObject 重複相同日誌碼,維護困難、違反 DRY 原則。
BusinessInterface 與實作 BusinessObject(純業務邏輯)。InvocationHandler:LogHandler 在 invoke() 中執行前後日誌,再透過反射呼叫真實物件方法。Proxy.newProxyInstance() 產生代理物件,透過介面呼叫。public class LogHandler implements InvocationHandler {
private Object delegate;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
logger.info("method starts: " + method);
Object result = method.invoke(delegate, args);
logger.info("method ends: " + method);
return result;
}
}
// 客戶端使用
BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(
businessImp.getClass().getClassLoader(),
businessImp.getClass().getInterfaces(),
new LogHandler(businessImp));
proxy.processBusiness();
INFO: method starts: processBusiness
here is business logic
INFO: method ends: processBusiness
JDK 動態代理單一 Handler 限制,實務上需自行維護 Handler 佇列或採用成熟框架(推薦 Spring)支援多重切面組合。
動態代理是 AOP 落地核心技術,掌握其原理有助於深入理解框架運作機制。