StateMachine - 对状态变化的操作

我使用 Spring 指南编写了状态机的实现。


但是,尽管状态本身已成功更改,但我无法对更改状态做出任何反应。也许我误解了 Beans 类的目标?我需要实现在状态发生变化时自动执行 closeDoor() 和 startMoving() 方法。


控制台方法中的这些消息不会显示:


import org.springframework.statemachine.annotation.OnTransition;

import org.springframework.statemachine.annotation.WithStateMachine;


@WithStateMachine

public class Beans {


  @OnTransition(target = "CLOSED_DOOR")

  void closeDoor() {

      System.out.println("closeDoor method");

  }


  @OnTransition(target = "GOING")

  void startMoving() {

      System.out.println("startMoving method");

  }

}


配置:


import org.springframework.statemachine.config.EnableStateMachine;

import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;

import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;

import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;;


import java.util.EnumSet;



@org.springframework.context.annotation.Configuration

@EnableStateMachine

public class Configuration extends EnumStateMachineConfigurerAdapter<States, Events> {

    @Override

    public void configure(StateMachineStateConfigurer<States, Events> states)

            throws Exception {

        states

                .withStates()

                .initial(States.STAY)

                .states(EnumSet.allOf(States.class));

    }


    @Override

    public void configure(StateMachineTransitionConfigurer<States, Events> transitions)

            throws Exception {

        transitions

                .withExternal()

                .source(States.STAY).target(States.CLOSED_DOOR)

                .event(Events.CLOSE_DOOR)

                .and()

                .withExternal()

                .source(States.CLOSED_DOOR).target(States.GOING)

                .event(Events.MOVE);

    }

}


蓝山帝景
浏览 125回答 1
1回答

梦里花落0921

最后,我设法让它发挥作用。您的问题是 Spring DI 机制。您试图使用@WithStateMachine来启用转换侦听器,但随后您正在使用.getMachine()来创建机器对象。它不会那样工作,您需要决定是否要使用 Spring Context。我已经使用上下文创建了一个解决方案,但您也可以保留它并仅使用手动构建器,但是您需要更改您的侦听器以使用手动方法而不是 Spring 上下文注释。将您的主类更改为:public class App {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; ConfigurableApplicationContext context = new AnnotationConfigApplicationContext("machine");&nbsp; &nbsp; &nbsp; &nbsp; final StateMachine<States, Events> stateMachine = context.getBean(StateMachine.class);&nbsp; &nbsp; &nbsp; &nbsp; stateMachine.start();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(stateMachine.getState()); // ObjectState [getIds()=[STAY]&nbsp; &nbsp; &nbsp; &nbsp; stateMachine.sendEvent(Events.CLOSE_DOOR);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(stateMachine.getState()); // ObjectState [getIds()=[CLOSED_DOOR]&nbsp; &nbsp; &nbsp; &nbsp; stateMachine.sendEvent(Events.MOVE);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(stateMachine.getState()); // ObjectState [getIds()=[GOING]&nbsp; &nbsp; }}让我知道它是否适合您以及您是否理解它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java