如何向弹簧状态机动作添加动态参数?

lou*_*ros 5 java spring spring-statemachine

我有这个简单的状态机配置:

@Configuration 
@EnableStateMachine 
public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapter<State, Boolean> {

    @Override
    public void configure(StateMachineStateConfigurer<State, Boolean> states) throws Exception {
        states.withStates()
                .initial(State.INITIAL)
                .states(EnumSet.allOf(State.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<State, Boolean> transitions) throws Exception {
        transitions
            .withExternal() 
                .source(State.INITIAL)
                .target(State.HAS_CUSTOMER_NUMBER)
                .event(true)
                .action(retrieveCustomerAction()) 
                // here I'd like to retrieve the customer from this action, like:
                // stateMachine.start();
                // stateMachine.sendEvent(true);
                // stateMachine.retrieveCustomerFromAction();
            .and()
            .withExternal()
                .source(State.INITIAL)
                .target(State.NO_CUSTOMER_NUMBER)
                .event(false)
                .action(createCustomerAction()); 
                // here I'd like to send the customer instance to create, like:
                // stateMachine.start();
                // stateMachine.sendEvent(false);
                // stateMachine.sendCustomerToAction(Customer customer);
    }

    @Bean
    public Action<State, Boolean> retrieveCustomerAction() {
        return ctx -> System.out.println(ctx.getTarget().getId());
    }

    @Bean
    public Action<State, Boolean> createCustomerAction() {
        return ctx -> System.out.println(ctx.getTarget().getId());
    }

}
Run Code Online (Sandbox Code Playgroud)

是否可以改进动作定义,以便能够通过动态参数与它们进行交互?我如何将消费者或提供者行为添加到这些操作中?

Vak*_*pta 2

是否可以改进动作定义,以便能够通过动态参数与它们进行交互?

是的,这是可能的。您可以将变量存储在上下文存储中,然后在任何您想要的地方检索。

public class Test {

  @Autowired
  StateMachine<State, Boolean> stateMachine;

  public void testMethod() {

    stateMachine.getExtendedState().getVariables().put(key, value);
    stateMachine.start();
    stateMachine.sendEvent(true);
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用键从上下文中检索该值。假设该值是 String 类型,那么可以像这样检索它:-

    @Bean
    public Action<State, Boolean> retrieveCustomerAction() {
        return ctx -> {
        String value = ctx.getExtendedState().get(key, String.class);
        // Do Something
        };
    }
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以参考链接这个

我如何将消费者或提供者行为添加到这些操作中?

你能详细说明一下这个问题吗