不使用表单如何在service task中获取变量并在Java Delegate中赋值
Java Delegate类变量赋值与空值异常解决方法
前置校验:Postman请求配置
不用表单提交时需传递JSON格式参数,配置要求如下:
- 请求头添加
Content-Type: application/json - 若直接调用Camunda原生REST接口启动流程,请求体需符合引擎变量传递规范,示例:
{ "variables": { "userId": { "value": "u001", "type": "String" }, "payAmount": { "value": 199.9, "type": "Double" } } }
- 若调用自定义业务接口,请求体直接传业务参数即可,需保证参数名和后续取值的变量名完全匹配,大小写敏感。
Java Delegate实现逻辑
实现JavaDelegate接口时,需优先处理变量非空逻辑,再赋值存库,完整示例如下:
import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Component("dataPersistDelegate") public class DataPersistDelegate implements JavaDelegate { // 注入你的持久层操作类 @Resource private OrderMapper orderMapper; @Override public void execute(DelegateExecution execution) throws Exception { // 1. 取流程变量,使用getVariableOrDefault设置默认值,避免直接抛出空指针 String userId = (String) execution.getVariableOrDefault("userId", ""); Double payAmount = (Double) execution.getVariableOrDefault("payAmount", 0.0); // 2. 业务层面非空校验,不符合要求直接抛出明确异常,提前拦截 if (userId.isBlank()) { throw new IllegalArgumentException("用户ID参数为空,请检查请求传参"); } if (payAmount <= 0) { throw new IllegalArgumentException("支付金额参数非法,请检查请求传参"); } // 3. 给存库实体类赋值 Order order = new Order(); order.setUserId(userId); order.setPayAmount(payAmount); // 4. 执行存库操作 orderMapper.insert(order); // 5. 若需要将存库结果返回为流程变量,调用setVariable方法赋值 execution.setVariable("newOrderId", order.getId()); } }
完成代码编写后,需在流程建模的Service Task配置项中,将Delegate表达式设置为${dataPersistDelegate},和你定义的Component名称保持一致。
自定义接口传参适配
如果没有直接调用Camunda原生启动接口,需在自定义Controller层接收参数后手动传入流程引擎,示例:
import org.camunda.bpm.engine.RuntimeService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.Map; @RestController public class ProcessController { @Resource private RuntimeService runtimeService; @PostMapping("/startOrderProcess") public String startProcess(@RequestBody Map<String, Object> requestParams) { // 提前校验入参非空 String userId = (String) requestParams.getOrDefault("userId", ""); if (userId.isBlank()) { throw new IllegalArgumentException("用户ID不能为空"); } // 启动流程时传入变量 runtimeService.startProcessInstanceByKey("order_process", requestParams); return "流程启动成功"; } }
内容的提问来源于stack exchange,提问作者Ano
相关产品推荐
相关产品推荐

