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);
}
commandExecutor.execute(new StartProcessInstanceCmd(...))。first(鏈頭攔截器)與 defaultConfig,調用 first.execute(config, command)。next.execute(config, command) 傳遞給下一個。command.execute(commandContext) 執行真正業務邏輯。| 攔截器 | 職責 |
|---|---|
LogInterceptor | 記錄命令執行日志、耗時統計 |
TransactionInterceptor | 管理事務邊界(開啟、提交、回滾) |
CommandContextInterceptor | 創建/綁定/清理 CommandContext(會話、緩存、實體管理器) |
SpringTransactionInterceptor | 整合 Spring 事務管理器 |
CommandContext 在鏈中隱式傳遞,為底層持久化、緩存提供線程級上下文。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 的緩存與持久化機制、以及流程定義解析器的工作原理。敬請期待。