jBPM 允許在流程定義 XML (processdefinition.xml) 中為 ActionHandler 實現類聲明屬性,引擎實例化時自動注入 (Setter Injection),實現配置與代碼分離。
package com.wfoxd.test;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;
public class MyActionHandler implements ActionHandler {
private static final long serialVersionUID = 1L;
// 測試用靜態標記
public static boolean isExecuted = false;
// 待注入屬性 (需提供 Setter)
private String nameTest;
private Integer number;
public void setNameTest(String nameTest) { this.nameTest = nameTest; }
public void setNumber(Integer number) { this.number = number; }
public void execute(ExecutionContext executionContext) {
isExecuted = true; // 標記已執行,便於單元測試驗證
System.out.println("Injected nameTest: " + nameTest);
System.out.println("Injected number: " + number);
// 業務邏輯:可訪問 executionContext 獲取 token、變數、任務等
}
}
<process-definition name="testActionInjection">
<start-state>
<transition to="decisionNode"></transition>
</start-state>
<decision name="decisionNode">
<!-- 節點進入動作:注入變數 -->
<action class="com.wfoxd.test.MyActionHandler">
<nameTest>WorkflowTest</nameTest>
<number>123</number>
</action>
<transition name="pathA" to="stateA"></transition>
<transition name="pathB" to="stateB"></transition>
</decision>
<state name="stateA"></state>
<state name="stateB"></state>
</process-definition>
<nameTest>) 必須與 Java Bean 屬性名 (nameTest) 完全一致 (大小寫敏感)。TypeConverter。execute(),執行結束實例可被 GC (無狀態設計)。isExecuted 為靜態僅供單元測試驗證,生產代碼嚴禁使用靜態狀態 (多執行緒併發會導致數據錯亂)。execute() 中可獲取 token、流程變數 (getVariable/setVariable)、任務實例、上下文實例等,實現完整業務邏輯。// 測試前重置
MyActionHandler.isExecuted = false;
// 載入流程定義、啟動流程實例、觸發節點
ProcessDefinition pd = ProcessDefinition.parseXmlResource("processdefinition.xml");
ProcessInstance pi = new ProcessInstance(pd);
pi.signal(); // 進入 decisionNode,觸發 Action
// 驗證
assertTrue(MyActionHandler.isExecuted);
// 進一步驗證注入值需在 execute 中設置到上下文或日誌檢查
DecisionHandler 實現動態路由規則外部化配置。