亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

StateMachine - 對狀態變化的操作

StateMachine - 對狀態變化的操作

藍山帝景 2023-01-05 17:13:19
我使用 Spring 指南編寫了狀態機的實現。但是,盡管狀態本身已成功更改,但我無法對更改狀態做出任何反應。也許我誤解了 Beans 類的目標?我需要實現在狀態發生變化時自動執行 closeDoor() 和 startMoving() 方法??刂婆_方法中的這些消息不會顯示:import org.springframework.statemachine.annotation.OnTransition;import org.springframework.statemachine.annotation.WithStateMachine;@WithStateMachinepublic 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@EnableStateMachinepublic 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);    }}
查看完整描述

1 回答

?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

最后,我設法讓它發揮作用。您的問題是 Spring DI 機制。您試圖使用@WithStateMachine來啟用轉換偵聽器,但隨后您正在使用.getMachine()來創建機器對象。它不會那樣工作,您需要決定是否要使用 Spring Context。我已經使用上下文創建了一個解決方案,但您也可以保留它并僅使用手動構建器,但是您需要更改您的偵聽器以使用手動方法而不是 Spring 上下文注釋。


將您的主類更改為:


public class App {


    public static void main(String[] args) {


        ConfigurableApplicationContext context = new AnnotationConfigApplicationContext("machine");

        final StateMachine<States, Events> stateMachine = context.getBean(StateMachine.class);


        stateMachine.start();

        System.out.println(stateMachine.getState()); // ObjectState [getIds()=[STAY]


        stateMachine.sendEvent(Events.CLOSE_DOOR);

        System.out.println(stateMachine.getState()); // ObjectState [getIds()=[CLOSED_DOOR]


        stateMachine.sendEvent(Events.MOVE);

        System.out.println(stateMachine.getState()); // ObjectState [getIds()=[GOING]

    }

}

讓我知道它是否適合您以及您是否理解它。


查看完整回答
反對 回復 2023-01-05
  • 1 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號