如何将动态参数添加到弹簧状态机动作中



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

@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());
}
}

是否有可能改进动作定义,使其能够与动力学参数相互作用?如何将消费者或提供者的行为添加到这些操作中?

是否可以改进动作定义以进行交互与他们的动力学参数?

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

public class Test {
@Autowired
StateMachine<State, Boolean> stateMachine;
public void testMethod() {
stateMachine.getExtendedState().getVariables().put(key, value);
stateMachine.start();
stateMachine.sendEvent(true);
}
}

您可以使用键从上下文中检索此值。假设该值的类型为String,则可以如下检索:-

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

有关更多信息,您可以参考链接和此

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

你能详细说明这个问题吗

最新更新