首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

AOP 系列之三:手把手教你用 Java 動態代理實作 AOP 核心機制

     編輯:Java 相關知識

前言:從 OOP 到 AOP 的思維轉換

AOP 近年風靡,Spring、JAC、JBoss AOP 等框架層出不窮。本文不依賴任何第三方框架,僅用 JDK 內建動態代理,以最簡單範例展示 AOP 核心運作原理,適合初學者快速入門。

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...");
        }
    }
}

缺點:日誌代碼散落於每個業務方法、維護困難、大量重複代碼。

動態代理實作 AOP 完整流程

1. 定義業務介面與實作(純淨版)

public interface BusinessInterface {
    void processBusiness();
}

public class BusinessObject implements BusinessInterface {
    public void processBusiness() {
        System.out.println("here is business logic");
    }
}

2. 撰寫通用攔截器

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;
    }
}

3. 客戶端建立代理並呼叫

BusinessInterface businessImpl = new BusinessObject();
InvocationHandler handler = new LogHandler(businessImpl);
BusinessInterface proxy = (BusinessInterface) Proxy.newProxyInstance(
    businessImpl.getClass().getClassLoader(),
    businessImpl.getClass().getInterfaces(),
    handler
);
proxy.processBusiness();

4. 執行結果

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 等主流框架的底層邏輯,並在框架無法滿足特殊需求時,具備自行擴充的能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved