1 回答

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]
}
}
讓我知道它是否適合您以及您是否理解它。
添加回答
舉報