问题
With spring state machine, we have states and events. I could not find any documentation on whether it is possible to attach static data to a state during configuration.
For example, if there are the states S1 and S2
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
states.withStates()
.initial("INIT")
.end("END")
.state("S1", null, exitAction())
.state("S2", entryAction());
}
If we could attach static data during the above configuration (like a java Map for example), it could be useful in the actions that are triggered (like entryAction and exitAction above)
I don't know if it is possible to do somehow.
回答1:
This is achieved with two objects in the state machine - StateContext and ExtendedState.
StateContext is like a current snapshot of the State Machine - it's passed around in various methods and callbacks, including actions and guards.
ExtendedState is basically a map with variables.
You can get the ExtendedState
from the StateContext
:
context.getExtendedState()
.getVariables().put("mykey", "myvalue");
As it is passed around as part of the context, you can access the ExtendedState
in every action, transition, guard etc.
The StateMachine object itself also has a getExtendedState()
method.
This is the canonical way to pass static data around in the StateMachine.
来源:https://stackoverflow.com/questions/54992727/spring-state-machine-attaching-static-data-to-states