spring-statemachine - 设置 Spring StateMachine 的当前状态
问题描述
我开始使用 Spring Statemachine,但在管理对象状态时遇到了一些麻烦。
我的 Statemachine 属于 StateMachine 类型。
我的业务对象 Shipment 有一个 ShipmentState 类型的枚举属性(状态),它应该保存剧集的状态机状态。这是我想要的工作流程:
- 从数据库加载货件。
- 从 Shipment 实例中的 ShipmentState 设置 Statemachine 的当前状态。
- 向状态机发送事件。
- 从 Statemachine(发布事件)获取结果状态并在我的 Shipmentinstance 中设置 ShipmentState。
- 保存 Shipment 实例。
问题是:如何设置现有 StateMachine 的当前状态?
我目前的方法是这样的:对于每个事件,创建一个新的 StateMachine 实例(使用 StateMachineBuilder),根据 Shipment 实例指定初始状态。例如:
@Service
public class StateMachineServiceImpl implements IStateMachineService {
@Autowired
private IShipmentService shipmentService;
@Override
public StateMachine<ShipmentState, ShipmentEvent> getShipmentStateMachine(Shipment aShipment) throws Exception {
Builder<ShipmentState, ShipmentEvent> builder = StateMachineBuilder.builder();
builder.configureStates().withStates()
.state(ShipmentState.S1)
.state(ShipmentState.S2)
.state(ShipmentState.S3)
.initial(shipmentService.getState())
.end(ShipmentState.S4);
builder.configureTransitions().withExternal().source(ShipmentState.S1).target(ShipmentState.S1)
.event(ShipmentEvent.S3).action(shipmentService.updateAction()).and().withExternal()
.source(ShipmentState.S1).target(ShipmentState.S2).event(ShipmentEvent.S3)
.action(shipmentService.finalizeAction()).and().withExternal().source(ShipmentState.S3)
.target(ShipmentEvent.S4).action(shipmentService.closeAction()).event(ShipmentEvent.S5);
return builder.build();
}
}
你觉得我的做法怎么样?
解决方案
这种方法没有问题。您可以使用以下代码将状态机重置为特定状态。
stateMachine.getStateMachineAccessor().doWithAllRegions(access -> access
.resetStateMachine(new DefaultStateMachineContext<>(state, null, null,null)));
您可以DefaultStateMachineContext
根据您的用例将参数传递给。
推荐阅读
- javascript - 即使 HTTP 响应为 200,Django 下载也没有开始
- c# - 小型主机游戏的 if 循环
- jquery - 当两个元素具有相同的计数值时,jquery隐藏元素
- java - 从 MongoDB 集合中查询超过 100 万条记录的最佳方法
- android - 访问 SD 卡时出错(没有这样的文件或目录)”文件可用,如设备文件资源管理器的屏幕截图所示
- java - 如何让 NVDA 读取 Swing / GUI 元素
- php - session_start(); 以及如何使用?
- json - Nifi-将json属性转换为executestreamcommand中的变量
- reactjs - 反应:道具数据未传递给子组件
- python - 用户定义的函数不适用于 Pandas