一、技术栈选型与架构设计
在构建企业级Java应用时,选择合适的技术栈至关重要。Spring MVC作为轻量级Web框架,提供清晰的MVC分层架构;MyBatis作为半自动ORM框架,兼具灵活性与性能优势;Activiti作为开源工作流引擎,支持BPMN 2.0标准规范。三者结合可构建出高扩展性的流程管理系统。
典型架构采用三层设计:
- 表现层:Spring MVC处理HTTP请求,结合Thymeleaf/FreeMarker实现视图渲染
- 业务层:Service组件封装核心逻辑,通过Spring事务管理保证数据一致性
- 数据层:MyBatis映射SQL与对象关系,Activiti引擎驱动流程流转
数据库设计需考虑三类表结构:
- 业务数据表(如订单表)
- 流程实例表(act_ru_execution)
- 历史记录表(act_hi_procinst)
二、Spring MVC核心配置实践
2.1 环境搭建与依赖管理
推荐使用Maven进行依赖管理,核心配置示例:
<dependencies><!-- Spring MVC基础 --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.20</version></dependency><!-- Servlet API --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency></dependencies>
2.2 关键组件配置
-
DispatcherServlet配置:
@Configurationpublic class WebConfig implements WebMvcConfigurer {@Beanpublic DispatcherServlet dispatcherServlet() {return new DispatcherServlet();}@Beanpublic ServletRegistrationBean<DispatcherServlet> servletRegistration() {return new ServletRegistrationBean<>(dispatcherServlet(), "/");}}
-
视图解析器配置:
# application.propertiesspring.mvc.view.prefix=/WEB-INF/views/spring.mvc.view.suffix=.jsp
2.3 控制器开发范式
推荐使用@RestController与@RequestMapping组合:
@RestController@RequestMapping("/api/orders")public class OrderController {@Autowiredprivate OrderService orderService;@GetMapping("/{id}")public ResponseEntity<OrderDTO> getOrder(@PathVariable Long id) {return ResponseEntity.ok(orderService.findById(id));}@PostMappingpublic ResponseEntity<OrderDTO> createOrder(@Valid @RequestBody OrderDTO dto) {return ResponseEntity.created(URI.create("/orders/" + orderService.save(dto).getId())).body(dto);}}
三、MyBatis持久层开发指南
3.1 基础映射配置
-
XML映射文件示例:
<mapper namespace="com.example.mapper.OrderMapper"><select id="findById" resultType="com.example.dto.OrderDTO">SELECT id, order_no, amountFROM t_orderWHERE id = #{id}</select><insert id="insert" useGeneratedKeys="true" keyProperty="id">INSERT INTO t_order(order_no, amount)VALUES(#{orderNo}, #{amount})</insert></mapper>
-
注解方式配置:
public interface OrderMapper {@Select("SELECT * FROM t_order WHERE id = #{id}")OrderDTO findById(@Param("id") Long id);@Options(useGeneratedKeys = true, keyProperty = "id")@Insert("INSERT INTO t_order(order_no, amount) VALUES(#{orderNo}, #{amount})")int insert(OrderDTO order);}
3.2 动态SQL高级应用
-
条件查询构建:
<select id="findByCondition" resultType="OrderDTO">SELECT * FROM t_order<where><if test="orderNo != null">AND order_no LIKE CONCAT('%', #{orderNo}, '%')</if><if test="minAmount != null">AND amount >= #{minAmount}</if></where>ORDER BY create_time DESC</select>
-
批量操作优化:
@Insert({"<script>","INSERT INTO t_order(order_no, amount) VALUES ","<foreach collection='orders' item='order' separator=','>","(#{order.orderNo}, #{order.amount})","</foreach>","</script>"})int batchInsert(@Param("orders") List<OrderDTO> orders);
四、Activiti工作流集成方案
4.1 流程引擎初始化
@Configurationpublic class ActivitiConfig {@Beanpublic ProcessEngineConfiguration processEngineConfiguration() {SpringProcessEngineConfiguration config = new SpringProcessEngineConfiguration();config.setDataSource(dataSource());config.setDatabaseSchemaUpdate("true");config.setAsyncExecutorActivate(false);return config;}@Beanpublic ProcessEngine processEngine() {return processEngineConfiguration().buildProcessEngine();}}
4.2 核心流程操作
-
流程部署与启动:
@Servicepublic class ProcessService {@Autowiredprivate RepositoryService repositoryService;@Autowiredprivate RuntimeService runtimeService;public void deployProcess(String bpmnPath) {Deployment deployment = repositoryService.createDeployment().addClasspathResource(bpmnPath).name("订单审批流程").deploy();}public String startProcess(String processKey, Map<String, Object> variables) {ProcessInstance instance = runtimeService.startProcessInstanceByKey(processKey, variables);return instance.getId();}}
-
任务处理逻辑:
@Servicepublic class TaskService {@Autowiredprivate TaskService taskService;public List<Task> getUserTasks(String userId) {return taskService.createTaskQuery().taskAssignee(userId).active().list();}public void completeTask(String taskId, Map<String, Object> variables) {taskService.complete(taskId, variables);}}
4.3 高级流程控制
- 会签处理实现:
```java
// 启动多实例任务
Map variables = new HashMap<>();
variables.put(“approvers”, Arrays.asList(“user1”, “user2”, “user3”));
variables.put(“nrOfInstances”, 3);
variables.put(“nrOfCompletedInstances”, 0);
// 完成时判断
runtimeService.setVariable(executionId, “nrOfCompletedInstances”,
(Integer)runtimeService.getVariable(executionId, “nrOfCompletedInstances”) + 1);
if ((Integer)runtimeService.getVariable(executionId, “nrOfCompletedInstances”)
>= (Integer)runtimeService.getVariable(executionId, "nrOfInstances")) {// 所有实例完成后的逻辑
}
2. **异常流程处理**:```java@RestControllerAdvicepublic class ProcessExceptionHandler {@ExceptionHandler(ActivitiException.class)public ResponseEntity<ErrorResponse> handleActivitiError(ActivitiException ex) {if (ex instanceof ActivitiObjectNotFoundException) {return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ErrorResponse("PROCESS_NOT_FOUND", ex.getMessage()));}return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorResponse("PROCESS_ERROR", ex.getMessage()));}}
五、系统集成与最佳实践
5.1 事务管理策略
-
分布式事务处理:
对于跨服务调用,推荐采用Saga模式或TCC模式。本地事务可通过@Transactional注解管理:@Service@Transactionalpublic class OrderProcessService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate RuntimeService runtimeService;public void submitOrderWithProcess(OrderDTO order) {// 保存业务数据orderMapper.insert(order);// 启动流程Map<String, Object> variables = new HashMap<>();variables.put("orderId", order.getId());runtimeService.startProcessInstanceByKey("orderProcess", variables);}}
5.2 性能优化方案
- 数据库优化:
- 为Activiti的ACTRU*表建立合适索引
- 定期归档历史数据到单独表空间
- 使用连接池配置(如HikariCP)
- 异步处理策略:
@Asyncpublic CompletableFuture<Void> asyncCompleteTask(String taskId) {try {taskService.complete(taskId);return CompletableFuture.completedFuture(null);} catch (Exception e) {return CompletableFuture.failedFuture(e);}}
5.3 监控与运维
-
流程监控面板:
@RestController@RequestMapping("/monitor")public class ProcessMonitorController {@Autowiredprivate HistoryService historyService;@GetMapping("/metrics")public Map<String, Object> getProcessMetrics() {Map<String, Object> metrics = new HashMap<>();metrics.put("runningInstances", historyService.createHistoricProcessInstanceQuery().unfinished().count());metrics.put("completedInstances", historyService.createHistoricProcessInstanceQuery().finished().count());return metrics;}}
-
日志集成方案:
```propertieslogback-spring.xml配置示例
logs/activiti.log
logs/activiti.%d{yyyy-MM-dd}.log
%d{yyyy-MM-dd HH
ss.SSS} [%thread] %-5level %logger{36} - %msg%n
```
六、总结与展望
本方案通过Spring MVC、MyBatis与Activiti的深度集成,构建了可扩展的企业级工作流系统。实际开发中需注意:
- 版本兼容性:Spring 5.x与Activiti 6.x/7.x的适配问题
- 流程版本控制:采用BPMN XML文件进行版本管理
- 异常处理机制:建立完善的流程回滚与补偿机制
未来发展方向包括:
- 引入规则引擎实现动态审批逻辑
- 结合低代码平台提升流程设计效率
- 采用微服务架构实现流程服务的独立部署
通过持续优化与技术创新,该技术栈可支撑从简单审批到复杂业务编排的各类场景需求,为企业数字化转型提供坚实的技术基础。