首页 > 解决方案 > 设置 Spring StateMachine 的当前状态

问题描述

我开始使用 Spring Statemachine,但在管理对象状态时遇到了一些麻烦。

我的 Statemachine 属于 StateMachine 类型。

我的业务对象 Shipment 有一个 ShipmentState 类型的枚举属性(状态),它应该保存剧集的状态机状态。这是我想要的工作流程:

问题是:如何设置现有 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();
    }

}

你觉得我的做法怎么样?

标签: spring-statemachine

解决方案


这种方法没有问题。您可以使用以下代码将状态机重置为特定状态。

stateMachine.getStateMachineAccessor().doWithAllRegions(access -> access
          .resetStateMachine(new DefaultStateMachineContext<>(state, null, null,null)));

您可以DefaultStateMachineContext根据您的用例将参数传递给。


推荐阅读