【问题标题】:Spring State Machine wont change state弹簧状态机不会改变状态
【发布时间】:2017-10-06 15:12:21
【问题描述】:

我正在尝试组装一个非常简单的 Spring 状态机,但它似乎不想改变状态:
(重要的是要注意,即使我使用的是 Spring State Machine,并且应用程序的其余部分是 Spring 应用程序,我也不能使用注释驱动的方法来定义机器。我必须使用构建器)

    StateMachineBuilder.Builder<String, String> builder = StateMachineBuilder.builder();

    try {
        builder.configureConfiguration()
                .withConfiguration()
                .beanFactory(new StaticListableBeanFactory())
                .listener(new StateMachineListenerAdapter<String, String>() {
                    @Override
                    public void stateChanged(State<String, String> from, State<String, String> to) {
                        System.out.println("State change to " + to.getId());
                    }
                });

        builder.configureStates()
                .withStates()
                .initial("initialState")
                .states(Stream.of("initialState", "state1", "state2", "state3").collect(Collectors.toSet()))
                .end("state3");

        builder.configureTransitions()
                .withExternal()
                .state("initialState")
                .target("state1")
                .event("event1")
                .action(stateContext ->
                    System.out.println(String.format("Event %s triggered", stateContext.getEvent()))
                );

    } catch (Exception e) {
        e.printStackTrace();
    }

    StateMachine<String, String> stateMachine = builder.build();

    stateMachine.start();

    boolean complete = stateMachine.isComplete();
    System.out.println("Statemachine is complete: " + complete);

    State<String, String> state = stateMachine.getState();
    System.out.println(state.getId());

    stateMachine.sendEvent("event1");

    state = stateMachine.getState();
    System.out.println(state.getId());

当我运行上述代码时,我期望第一个状态是initialState,当我发送事件event1 时,状态将更改为state1。我得到以下输出:

State change to initialState
Statemachine is complete: false
initialState
initialState

这告诉我监听器在机器第一次启动并设置初始状态时触发一次,由于某种原因状态机报告它不完整,在我发送事件之前状态为initialState,并且状态我发送事件后仍然是initialState
启动状态机或发送事件时都没有错误,并且转换中的操作永远不会运行。

我错过了什么?

【问题讨论】:

    标签: spring-statemachine


    【解决方案1】:

    我发现了问题 - 我错误地配置了转换!
    应该是这样的:

        builder.configureTransitions()
                .withExternal()
                .source("initialState")
                .target("state1")
                .event("event1")
                .action(stateContext ->
                    System.out.println(String.format("Event %s triggered", stateContext.getEvent()))
                );
    

    IE。我本来是打电话给.state的,本来应该是.source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      相关资源
      最近更新 更多