Spring State Machine - Attaching static data to states

孤者浪人 提交于 2020-05-07 08:17:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!