一、引言
在企業級應用開發中,工作流管理是不可或缺的一部分。從簡單的請假審批到復雜的業務流程,工作流引擎能夠顯著提升系統的靈活性和可維護性。??Flowable?? 作為一個輕量級、基于 Java 的開源工作流引擎,完美支持 ??BPMN 2.0?? 標準,廣泛應用于各類業務流程管理場景。
??Spring Boot?? 憑借其快速開發、自動配置等特性,已成為現代 Java 開發的主流框架。將 ??Spring Boot 3?? 與 ??Flowable 7.1.0?? 集成,不僅能夠快速構建功能強大的工作流應用,還能極大地簡化開發流程,提高開發效率。
本教程將從環境準備、依賴配置、數據庫設置、流程引擎初始化、流程設計與部署、流程運行與監控等多個方面,詳細介紹如何將 Spring Boot 3 與 Flowable 7.1.0 進行深度集成,幫助開發者快速上手并構建專業級的工作流系統。
二、環境準備
在開始集成之前,確保您的開發環境滿足以下要求:
- ??JDK??: 推薦使用 JDK 17 或更高版本(本教程以 JDK 21 為例)
- ??IDE??: IntelliJ IDEA、Eclipse 等主流 Java IDE
- ??構建工具??: Maven 或 Gradle(本教程以 Maven 為例)
- ??數據庫??: MySQL 8.0(也可根據需要選擇其他支持的數據庫)
- ??Flowable 版本??: 7.1.0
- ??Spring Boot 版本??: 3.4.1(根據實際情況選擇)
三、創建 Spring Boot 項目
您可以使用 Spring Initializr 快速創建一個新的 Spring Boot 項目,或者手動創建一個 Maven 項目。以下是主要步驟:
1. 使用 Spring Initializr 創建項目
- 訪問 Spring Initializr
- 配置項目基本信息:
- ??Project??: Maven Project
- ??Language??: Java
- ??Spring Boot??: 3.4.1(根據最新版本選擇)
- ??Group??: com.example(根據實際情況修改)
- ??Artifact??: flowable-demo(根據實際情況修改)
- ??Name??: flowable-demo
- ??Package name??: com.example.flowabledemo
- ??Packaging??: Jar
- ??Java??: 21
- 添加依賴:
- ??Spring Web??
- ??Spring Data JPA??(可選,根據需要)
- ??MySQL Driver??
- ??Spring Security??(可選,根據需要)
- 生成并下載項目,導入到您的 IDE 中。
2. 手動創建 Maven 項目
如果您選擇手動創建 Maven 項目,確保 pom.xml
包含以下基本配置:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>flowable-demo</artifactId><version>1.0.0</version><packaging>jar</packaging><name>Flowable Demo</name><properties><java.version>21</java.version><spring-boot.version>3.4.1</spring-boot.version><flowable.version>7.1.0</flowable.version></properties><dependencies><!-- 待添加 --></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>${spring-boot.version}</version></plugin></plugins></build>
</project>
四、添加依賴
在 pom.xml
中添加 Spring Boot 和 Flowable 7.1.0 所需的依賴。以下是一個完整的依賴配置示例:
<dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Starter Data JPA (可選,根據需要) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- MySQL 驅動 --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency><!-- Flowable Spring Boot Starter --><dependency><groupId>org.flowable</groupId><artifactId>flowable-spring-boot-starter</artifactId><version>${flowable.version}</version></dependency><!-- Spring Boot Starter Security (可選,根據需要) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!-- Lombok (可選,簡化代碼) --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- 其他依賴根據需要添加 -->
</dependencies>
??說明:??
- ??flowable-spring-boot-starter??: 這是 Flowable 提供的 Spring Boot 啟動器,包含了集成所需的核心依賴。
- ??spring-boot-starter-security??: 如果您的應用需要權限控制,可以添加此依賴。
- ??Lombok??: 可選,用于簡化 Java 類的代碼,如自動生成 Getter、Setter 等。
確保在 <properties>
中定義了 Flowable 和 Spring Boot 的版本:
<properties><java.version>21</java.version><spring-boot.version>3.4.1</spring-boot.version><flowable.version>7.1.0</flowable.version>
</properties>
五、配置數據庫與 Flowable
1. 配置 application.yml
在 src/main/resources/application.yml
中配置數據源和 Flowable 相關參數。以下是一個基于 MySQL 的配置示例:
server:port: 8080spring:datasource:url: jdbc:mysql://localhost:3306/flowable_db?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=trueusername: rootpassword: your_password # 替換為您的 MySQL 密碼driver-class-name: com.mysql.cj.jdbc.Drivertype: com.zaxxer.hikari.HikariDataSource # 推薦使用 HikariCP 作為連接池jpa:hibernate:ddl-auto: none # 根據需要配置,通常 Flowable 會自行管理其表show-sql: trueproperties:hibernate:dialect: org.hibernate.dialect.MySQLDialectflowable:async-executor-activate: false # 開發階段建議關閉異步執行器database-schema-update: true # 啟動時自動創建或更新數據庫表,生產環境建議設置為 falsehistory-level: audit # 歷史記錄級別,可選:none, activity, audit, full# process-definition-location-prefix: classpath:/processes/ # 流程定義文件存放路徑,根據需要配置
??配置說明:??
- ??server.port??: 應用啟動端口,可以根據需要修改。
- ??spring.datasource??: 配置 MySQL 數據源,確保數據庫
flowable_db
已存在,或者 Flowable 能夠自動創建(根據數據庫權限)。- ??url??: 數據庫連接地址,確保數據庫名稱(如
flowable_db
)正確。 - ??username?? 和 ??password??: 數據庫用戶名和密碼。
- ??driver-class-name??: MySQL JDBC 驅動類名。
- ??type??: 推薦使用 HikariCP 作為連接池,性能更優。
- ??url??: 數據庫連接地址,確保數據庫名稱(如
- ??spring.jpa??: 配置 JPA 相關參數。
- ??hibernate.ddl-auto??: 設置為
none
,避免與 Flowable 的表管理沖突。Flowable 會自行管理其數據庫表。 - ??show-sql??: 設置為
true
,方便調試時查看生成的 SQL 語句。 - ??properties.hibernate.dialect??: 設置 Hibernate 方言為 MySQL。
- ??hibernate.ddl-auto??: 設置為
- ??flowable??:
- ??async-executor-activate??: 開發階段建議設置為
false
,避免不必要的異步任務。生產環境可根據需要啟用。 - ??database-schema-update??: 設置為
true
,應用啟動時會自動創建或更新 Flowable 所需的數據庫表。??生產環境強烈建議設置為false
,并通過數據庫遷移工具(如 Flyway 或 Liquibase)管理數據庫 schema。?? - ??history-level??: 設置歷史記錄級別,
audit
級別會記錄較詳細的歷史信息,根據需求可選擇none
,activity
,audit
,full
。 - ??process-definition-location-prefix??: 如果您將 BPMN 流程定義文件存放在特定目錄(如
classpath:/processes/
),可以在此配置,Flowable 啟動時會自動部署這些流程定義。
- ??async-executor-activate??: 開發階段建議設置為
2. 數據庫準備
確保您已經安裝并運行了 MySQL 數據庫,并創建了用于 Flowable 的數據庫。例如,創建名為 flowable_db
的數據庫:
CREATE DATABASE flowable_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
??注意:?? 根據您的配置,確保數據庫名稱、用戶名和密碼與 application.yml
中的配置一致。
六、配置 Flowable
Spring Boot 與 Flowable 的集成主要通過自動配置完成,但您也可以根據需要進行自定義配置。
1. 自動配置
引入 flowable-spring-boot-starter
后,Spring Boot 會自動配置 Flowable 的核心 Bean,包括 ProcessEngine
、RuntimeService
、TaskService
、RepositoryService
、HistoryService
等。您無需手動配置這些 Bean,除非有特殊需求。
2. 自定義 Flowable 配置(可選)
如果需要自定義 Flowable 的配置,可以創建一個配置類實現 ProcessEngineConfigurationConfigurer
接口。例如,配置郵件服務器或自定義表單類型。
package com.example.flowabledemo.config;import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.form.api.FormEngine;
import org.flowable.form.api.FormRepositoryService;
import org.flowable.form.api.FormService;
import org.flowable.mail.api.MailEngine;
import org.springframework.context.annotation.Configuration;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;@Configuration
public class FlowableConfig implements ProcessEngineConfigurationConfigurer {@Overridepublic void configure(SpringProcessEngineConfiguration configuration) {// 示例:配置郵件服務器(根據需要)/*configuration.setMailServerHost("smtp.example.com");configuration.setMailServerPort(587);configuration.setMailServerUsername("notifications@example.com");configuration.setMailServerPassword("password");configuration.setMailServerDefaultFrom("notifications@example.com");*/// 示例:配置自定義表單類型(根據需要)/*List<FormEngine> customFormEngines = new ArrayList<>();// 添加自定義 FormEngineconfiguration.setCustomFormEngines(customFormEngines);List<FormType> customFormTypes = new ArrayList<>();// 添加自定義 FormTypeconfiguration.setCustomFormTypes(customFormTypes);*/// 其他自定義配置}
}
??說明:??
- 通過實現
ProcessEngineConfigurationConfigurer
接口,您可以在 Flowable 初始化時自定義其配置。 - 上述示例中注釋掉了郵件服務器和自定義表單類型的配置,您可以根據實際需求進行配置。
七、流程設計與部署
1. 使用 Flowable Modeler 設計流程
??Flowable Modeler?? 是 Flowable 提供的可視化流程設計工具,您可以通過它設計 BPMN 2.0 流程定義。
1.1 部署 Flowable Modeler
Flowable Modeler 通常作為一個獨立的服務運行。您可以通過 Docker 快速部署 Flowable Modeler:
docker run -d -p 9096:8080 --name flowable-modeler \-e FLOWABLE_COMMON_APP_IDM-URL=http://localhost:8080/flowable-idm \-e FLOWABLE_COMMON_APP_IDM-REDIRECT-ON-ERROR=true \flowable/flowable-modeler:7.1.0
??說明:??
- 上述命令將 Flowable Modeler 部署在
http://localhost:9096
。 - 您需要根據實際情況配置 IDM(身份管理)服務的 URL,如果使用獨立的 Flowable IDM,確保其運行并配置正確。
??注意:?? 本教程重點在于 Spring Boot 與 Flowable 的集成,若您不需要使用 Flowable Modeler 的圖形化設計功能,可以直接在項目中編寫 BPMN 文件。
1.2 使用獨立 Modeler 服務(可選)
如果您選擇使用獨立的 Flowable Modeler 服務,可以按照以下步驟操作:
-
??下載并部署 Flowable Modeler??:
- 訪問 Flowable 官方 Docker 鏡像 或 Flowable 官方文檔 獲取最新的 Modeler 鏡像。
- 使用 Docker 運行 Modeler,如上所示。
-
??配置跨域與數據庫??:
- 確保 Modeler 服務與您的 Spring Boot 應用使用相同的數據庫,或者根據需要進行配置。
- 配置跨域支持,以便前端能夠與后端服務通信。
??注意:?? 為了簡化流程,本教程將重點放在直接在 Spring Boot 項目中管理和部署 BPMN 文件。
2. 在項目中管理 BPMN 文件
您可以直接在 Spring Boot 項目的 src/main/resources/processes
目錄下存放 BPMN 2.0 文件,Flowable 啟動時會自動部署這些流程定義。
2.1 創建流程目錄
在 src/main/resources
下創建一個 processes
目錄,用于存放 BPMN 文件。
src
└── main└── resources└── processes└── leave-process.bpmn20.xml
2.2 編寫 BPMN 文件
以下是一個簡單的請假流程 (leave-process.bpmn20.xml
) 示例:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"xmlns:flowable="http://flowable.org/bpmn"targetNamespace="http://flowable.org/examples"><process id="leaveProcess" name="Leave Process" isExecutable="true"><startEvent id="startEvent" /><sequenceFlow id="flow1" sourceRef="startEvent" targetRef="approveTask" /><userTask id="approveTask" name="Approve Leave" flowable:assignee="${assignee}" /><sequenceFlow id="flow2" sourceRef="approveTask" targetRef="endEvent" /><endEvent id="endEvent" /></process></definitions>
??說明:??
- 這是一個非常簡單的請假流程,包含一個開始事件、一個用戶任務(審批任務)和一個結束事件。
flowable:assignee="${assignee}"
表示任務的辦理人通過流程變量assignee
動態指定。
??注意:?? 您可以根據實際業務需求設計更復雜的流程,包括網關、多個任務、事件等。
八、創建 Spring Boot 應用主類
確保您的 Spring Boot 應用有一個主類,用于啟動應用。例如:
package com.example.flowabledemo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class FlowableDemoApplication {public static void main(String[] args) {SpringApplication.run(FlowableDemoApplication.class, args);}
}
九、流程運行與操作
1. 自動部署流程
當您在 src/main/resources/processes
目錄下放置 BPMN 文件并啟動 Spring Boot 應用時,Flowable 會自動掃描并部署這些流程定義。
??驗證流程部署:??
您可以通過訪問 Flowable 提供的 REST API 或編寫簡單的測試控制器來驗證流程是否已成功部署。
2. 編寫流程操作控制器
為了與流程引擎交互,您可以編寫一個 REST 控制器,提供啟動流程、完成任務等接口。
2.1 添加依賴(如果尚未添加)
確保您的項目中包含 Spring Web 依賴,以支持 REST API。
2.2 創建流程服務類
首先,創建一個服務類,用于封裝與 Flowable 引擎的交互邏輯。
package com.example.flowabledemo.service;import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.HashMap;
import java.util.Map;@Service
public class FlowableService {@Autowiredprivate RuntimeService runtimeService;@Autowiredprivate TaskService taskService;/*** 啟動流程實例* @param processDefinitionKey 流程定義 Key,對應 BPMN 中的 process id* @param variables 流程變量* @return 啟動的流程實例 ID*/public String startProcess(String processDefinitionKey, Map<String, Object> variables) {ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);return processInstance.getId();}/*** 查詢用戶的待辦任務* @param assignee 辦理人* @return 待辦任務列表*/public List<Task> getTasksByAssignee(String assignee) {return taskService.createTaskQuery().taskAssignee(assignee).list();}/*** 完成任務* @param taskId 任務 ID* @param variables 任務變量*/public void completeTask(String taskId, Map<String, Object> variables) {taskService.complete(taskId, variables);}
}
2.3 創建 REST 控制器
接下來,創建一個 REST 控制器,暴露啟動流程和完成任務的接口。
package com.example.flowabledemo.controller;import com.example.flowabledemo.service.FlowableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.List;
import java.util.Map;@RestController
@RequestMapping("/api/flowable")
public class FlowableController {@Autowiredprivate FlowableService flowableService;/*** 啟動請假流程* @param assignee 辦理人* @return 流程實例 ID*/@PostMapping("/startLeaveProcess")public Map<String, String> startLeaveProcess(@RequestParam String assignee) {Map<String, Object> variables = new HashMap<>();variables.put("assignee", assignee);String processInstanceId = flowableService.startProcess("leaveProcess", variables);Map<String, String> response = new HashMap<>();response.put("processInstanceId", processInstanceId);return response;}/*** 獲取指定辦理人的待辦任務* @param assignee 辦理人* @return 待辦任務列表*/@GetMapping("/tasks")public List<?> getTasks(@RequestParam String assignee) {return flowableService.getTasksByAssignee(assignee);}/*** 完成任務* @param taskId 任務 ID* @param approved 是否批準(示例變量)* @return 操作結果*/@PostMapping("/completeTask")public Map<String, String> completeTask(@RequestParam String taskId, @RequestParam boolean approved) {Map<String, Object> variables = new HashMap<>();variables.put("approved", approved);flowableService.completeTask(taskId, variables);Map<String, String> response = new HashMap<>();response.put("message", "任務已完成");return response;}
}
??API 說明:??
-
??啟動請假流程??
- ??URL??:
POST /api/flowable/startLeaveProcess?assignee=用戶名
- ??描述??: 啟動一個請假流程實例,并指定任務的辦理人。
- ??示例請求??:
curl -X POST "http://localhost:8080/api/flowable/startLeaveProcess?assignee=user1"
- ??響應??:
{"processInstanceId": "12345" }
- ??URL??:
-
??獲取待辦任務??
- ??URL??:
GET /api/flowable/tasks?assignee=用戶名
- ??描述??: 查詢指定辦理人的待辦任務列表。
- ??示例請求??:
curl "http://localhost:8080/api/flowable/tasks?assignee=user1"
- ??響應??:
[{"id": "task1","name": "Approve Leave","assignee": "user1","created": "...","dueDate": "...",...} ]
- ??URL??:
-
??完成任務??
- ??URL??:
POST /api/flowable/completeTask?taskId=任務ID&approved=true|false
- ??描述??: 完成指定的任務,并傳遞是否批準等變量。
- ??示例請求??:
curl -X POST "http://localhost:8080/api/flowable/completeTask?taskId=task1&approved=true"
- ??響應??:
{"message": "任務已完成" }
- ??URL??:
??注意:??
- 確保流程定義中的
process id
(在 BPMN 文件中為<process id="leaveProcess" ...>
)與控制器中使用的processDefinitionKey
一致。 - 根據實際業務需求,您可以擴展更多的流程操作,如查詢流程實例、歷史記錄、任務表單等。
十、流程監控與歷史記錄
Flowable 提供了強大的歷史記錄和監控功能,您可以通過 HistoryService
查詢歷史流程實例、任務等信息。
1. 查詢歷史流程實例
您可以在服務類中添加方法,使用 HistoryService
查詢歷史記錄。例如:
package com.example.flowabledemo.service;import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class HistoryService {@Autowiredprivate HistoryService historyService;/*** 查詢歷史流程實例* @param processInstanceBusinessKey 業務鍵* @return 歷史流程實例列表*/public List<HistoricProcessInstance> getHistoricProcessInstancesByBusinessKey(String processInstanceBusinessKey) {return historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(processInstanceBusinessKey).list();}
}
??注意:?? 您需要在啟動流程時設置業務鍵,例如:
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leaveProcess", processInstanceBusinessKey, variables);
然后在控制器中添加相應的接口,供前端或其他服務查詢歷史記錄。
十一、生產環境最佳實踐
在生產環境中,集成 Flowable 需要注意以下最佳實踐,以確保系統的穩定性、安全性和性能。
1. 流程版本管理
隨著業務需求的變化,流程定義可能需要不斷迭代。Flowable 支持流程版本管理,確保新舊版本的流程定義能夠共存,并根據需要啟動不同版本的流程實例。
??操作步驟:??
- ??部署新版本流程??:每次更新 BPMN 文件后,將其重新部署,Flowable 會自動為新的流程定義分配一個新的版本號。
- ??保留歷史版本??:通過配置,Flowable 會保留所有歷史版本的流程定義,您可以根據需要啟動特定版本的流程實例。
??示例:??
將更新后的 leave-process-v2.bpmn20.xml
文件放置在 src/main/resources/processes
目錄下,啟動應用后,Flowable 會自動部署新版本,并為其分配新的版本號。
2. 表單集成方案
Flowable 支持內嵌表單和外置表單兩種方式,根據業務需求選擇合適的表單集成方案。
- ??內嵌表單??:在 BPMN 文件中通過
flowable:formField
定義表單字段,通過TaskService.getTaskFormData()
獲取表單元數據。 - ??外置表單??:使用 Flowable Form 引擎,支持 HTML/CSS/JavaScript 自定義表單,提供更靈活的用戶界面。
??推薦:?? 對于復雜表單需求,推薦使用外置表單,以實現更高的自定義程度和用戶體驗。
3. 監控與審計
通過 Flowable 提供的 HistoryService
和 ManagementService
,您可以實現流程的全面監控與審計。
- ??查詢流程執行歷史??:了解流程實例的執行情況、任務處理情況等。
- ??審計日志??:記錄關鍵操作和流程變更,確保流程的透明性和可追溯性。
??示例:??
List<HistoricProcessInstance> instances = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey("process_123").list();
4. 安全加固
確保 Flowable 集成系統的安全性,防止未經授權的訪問和潛在的安全漏洞。
- ??權限控制??:通過 Spring Security 或其他安全框架,限制對 Flowable API 的訪問,確保只有授權用戶才能啟動、處理流程。
- ??流程變量加密??:對敏感的流程變量進行加密存儲,保護用戶數據的隱私。
- ??防 SQL 注入??:使用 MyBatis 的
#{}
占位符或 JPA 的參數綁定,避免用戶輸入直接拼接到 SQL 語句中,防止 SQL 注入攻擊。
十二、性能優化
為了確保 Flowable 在生產環境中的高效運行,您可以采取以下性能優化措施:
1. 數據庫索引優化
為常用的查詢字段添加數據庫索引,提高查詢性能。例如,為 ACT_RU_TASK
表中的 ASSIGNEE_
字段添加索引。
??示例:??
Flowable 通常會自動管理其數據庫表的索引,但您可以根據具體查詢需求,手動創建額外的索引。
// 通常不需要手動創建索引,Flowable 自動管理
// 但在特定情況下,您可以通過 ManagementService 執行自定義 SQL
??注意:?? 生產環境中,建議通過數據庫管理員或使用數據庫遷移工具管理索引,確保索引的有效性和性能。