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

Activiti 源碼深度解析(一):命令模式與責任鏈模式的完美融合

     編輯:Java 綜合教學

Activiti 源碼深度解析(一):命令模式與責任鏈模式的完美融合

Activiti 核心引擎通過七大 Service 接口對外提供服務。深入源碼會發現,所有 Service 實現類的方法幾乎都委託給 CommandExecutor.execute(Command) 執行。這背後是命令模式與責任鏈模式的經典結合,構成了引擎核心的執行骨架。

核心類結構概覽

三大核心接口位於 org.activiti.engine.impl.interceptor 包:

// 1. 命令接口:封裝具體業務邏輯
public interface Command<T> {
    T execute(CommandContext commandContext);
}

// 2. 命令執行器:統一入口
public interface CommandExecutor {
    CommandConfig getDefaultConfig();
    <T> T execute(CommandConfig config, Command<T> command);
    <T> T execute(Command<T> command);
}

// 3. 命令攔截器:責任鏈節點
public interface CommandInterceptor {
    <T> T execute(CommandConfig config, Command<T> command);
    CommandInterceptor getNext();
    void setNext(CommandInterceptor next);
}

執行流程圖解

  1. Service 層:調用 commandExecutor.execute(new StartProcessInstanceCmd(...))。
  2. CommandExecutorImpl:持有 first(鏈頭攔截器)與 defaultConfig,調用 first.execute(config, command)。
  3. 攔截器鏈:每個攔截器完成各自職責(事務、日志、緩存、權限等),然後調用 next.execute(config, command) 傳遞給下一個。
  4. 終端攔截器:鏈尾調用 command.execute(commandContext) 執行真正業務邏輯。

關鍵攔截器實現(部分)

攔截器職責
LogInterceptor記錄命令執行日志、耗時統計
TransactionInterceptor管理事務邊界(開啟、提交、回滾)
CommandContextInterceptor創建/綁定/清理 CommandContext(會話、緩存、實體管理器)
SpringTransactionInterceptor整合 Spring 事務管理器

為什麼這樣設計?

  • 關注點分離:業務邏輯與事務、日志、安全等橫切關注點完全解耦。
  • 擴展性極強:新增攔截器只需在鏈中插入,無需修改現有代碼(開閉原則)。
  • 統一異常處理:頂層攔截器可統一捕獲異常、轉換、記錄、拋出。
  • 上下文傳遞:CommandContext 在鏈中隱式傳遞,為底層持久化、緩存提供線程級上下文。

代碼片段:CommandExecutorImpl 核心邏輯

public class CommandExecutorImpl implements CommandExecutor {
    private final CommandConfig defaultConfig;
    private final CommandInterceptor first; // 鏈頭

    public CommandExecutorImpl(CommandConfig defaultConfig, CommandInterceptor first) {
        this.defaultConfig = defaultConfig;
        this.first = first;
    }

    @Override
    public <T> T execute(Command<T> command) {
        return execute(defaultConfig, command);
    }

    @Override
    public <T> T execute(CommandConfig config, Command<T> command) {
        return first.execute(config, command); // 委託給鏈頭
    }
}

下一期預告

下篇將深入剖析 CommandContext 的生命周期管理、EntityManager 的緩存與持久化機制、以及流程定義解析器的工作原理。敬請期待。

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