Spring 状态机 - 将静态数据附加到状态
Spring State Machine - Attaching static data to states
使用 spring 状态机,我们有状态和事件。我找不到任何关于是否可以在配置期间将静态数据附加到状态的文档。
例如,如果有状态S1和S2
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
states.withStates()
.initial("INIT")
.end("END")
.state("S1", null, exitAction())
.state("S2", entryAction());
}
如果我们可以在上述配置期间附加静态数据(例如 java Map),它可能在触发的操作中很有用(例如上面的 entryAction 和 exitAction)
不知道有没有办法做。
这是通过状态机中的两个对象实现的 - StateContext and ExtendedState。
StateContext 就像状态机的当前快照 - 它在各种方法和回调中传递,包括动作和守卫。
ExtendedState 基本上是一个带有变量的映射。
您可以从 StateContext
:
得到 ExtendedState
context.getExtendedState()
.getVariables().put("mykey", "myvalue");
由于它作为上下文的一部分传递,您可以在每个动作、转换、守卫等中访问 ExtendedState
。
StateMachine 对象本身也有一个 getExtendedState()
方法。
这是在 StateMachine 中传递静态数据的规范方式。
使用 spring 状态机,我们有状态和事件。我找不到任何关于是否可以在配置期间将静态数据附加到状态的文档。
例如,如果有状态S1和S2
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
states.withStates()
.initial("INIT")
.end("END")
.state("S1", null, exitAction())
.state("S2", entryAction());
}
如果我们可以在上述配置期间附加静态数据(例如 java Map),它可能在触发的操作中很有用(例如上面的 entryAction 和 exitAction)
不知道有没有办法做。
这是通过状态机中的两个对象实现的 - StateContext and ExtendedState。
StateContext 就像状态机的当前快照 - 它在各种方法和回调中传递,包括动作和守卫。
ExtendedState 基本上是一个带有变量的映射。
您可以从 StateContext
:
ExtendedState
context.getExtendedState()
.getVariables().put("mykey", "myvalue");
由于它作为上下文的一部分传递,您可以在每个动作、转换、守卫等中访问 ExtendedState
。
StateMachine 对象本身也有一个 getExtendedState()
方法。
这是在 StateMachine 中传递静态数据的规范方式。