我正在尝试组建一个非常简单的Spring State Machine,但它似乎并不想改变状态:
(重要的是要注意,即使我使用的是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
在启动状态机或发送事件时没有错误,并且转换中的操作永远不会运行。
我错过了什么?
答案 0 :(得分:0)
我发现了问题 - 我正在错误地配置转换!
这应该是这样的:
builder.configureTransitions()
.withExternal()
.source("initialState")
.target("state1")
.event("event1")
.action(stateContext ->
System.out.println(String.format("Event %s triggered", stateContext.getEvent()))
);
IE。我最初打电话给.state
,应该是.source