如何向弹簧状态机动作添加动态参数?
来源:爱站网时间:2021-09-16编辑:网友分享
我有一个简单的状态机配置:@Configuration @EnableStateMachine公共类SimpleStateMachineConfiguration扩展了StateMachineConfigurerAdapter
{@ ...
问题描述
我有这个简单的状态机配置:
@Configuration
@EnableStateMachine
public class SimpleStateMachineConfiguration extends StateMachineConfigurerAdapter {
@Override
public void configure(StateMachineStateConfigurer states) throws Exception {
states.withStates()
.initial(State.INITIAL)
.states(EnumSet.allOf(State.class));
}
@Override
public void configure(StateMachineTransitionConfigurer 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 retrieveCustomerAction() {
return ctx -> System.out.println(ctx.getTarget().getId());
}
@Bean
public Action createCustomerAction() {
return ctx -> System.out.println(ctx.getTarget().getId());
}
}
是否有可能改善动作定义,使其能够与动力学参数进行交互?如何将消费者或提供者的行为添加到这些操作中?
思路:
是否有可能改进动作定义以进行交互与他们一起使用动力学参数?
是的,有可能。您可以将变量存储在上下文存储中,然后在任何需要的位置进行检索。
public class Test {
@Autowired
StateMachine stateMachine;
public void testMethod() {
stateMachine.getExtendedState().getVariables().put(key, value);
stateMachine.start();
stateMachine.sendEvent(true);
}
}
并且您可以使用键从上下文中检索此值。假设该值是String类型的,则可以像这样检索它:-
@Bean
public Action retrieveCustomerAction() {
return ctx -> {
String value = ctx.getExtendedState().get(key, String.class);
// Do Something
};
}
如何向这些操作添加消费者或提供者的行为?
您能否详细说明这个问题