Spring StateMachine - 从数据库配置

Spring StateMachine - Configure from Database

我在网上查到的所有例子中,StateMachine都是静态配置的

 @Override
public void configure(StateMachineTransitionConfigurer<BookStates, BookEvents> transitions) throws Exception {
    transitions
            .withExternal()
            .source(BookStates.AVAILABLE)
            .target(BookStates.BORROWED)
            .event(BookEvents.BORROW)
            .and()
            .withExternal()
            .source(BookStates.BORROWED)
            .target(BookStates.AVAILABLE)
            .event(BookEvents.RETURN)
            .and()
            .withExternal()
            .source(BookStates.AVAILABLE)
            .target(BookStates.IN_REPAIR)
            .event(BookEvents.START_REPAIR)
            .and()
            .withExternal()
            .source(BookStates.IN_REPAIR)
            .target(BookStates.AVAILABLE)
            .event(BookEvents.END_REPAIR);
 }

我想通过从数据库中获取源、目标、事件来配置 StateMachine "dynamically",然后循环遍历列表以 "fluid" 方式配置它。

这可能吗?

是的,可以通过 StateMachineModelFactory. You can hook it using StateMachineModelConfigurer 的自定义实现,如下所示:

@Configuration
@EnableStateMachine
public static class Config1 extends StateMachineConfigurerAdapter<String, String> {

    @Override
    public void configure(StateMachineModelConfigurer<String, String> model) throws Exception {
        model
            .withModel()
                .factory(modelFactory());
    }

    @Bean
    public StateMachineModelFactory<String, String> modelFactory() {
        return new CustomStateMachineModelFactory();
    }
}

在您的实现中,您可以从外部服务动态加载 SM 模型所需的任何内容。以下是来自 official doc:

的示例
public static class CustomStateMachineModelFactory implements StateMachineModelFactory<String, String> {

    @Override
    public StateMachineModel<String, String> build() {
        ConfigurationData<String, String> configurationData = new ConfigurationData<>();
        Collection<StateData<String, String>> stateData = new ArrayList<>();
        stateData.add(new StateData<String, String>("S1", true));
        stateData.add(new StateData<String, String>("S2"));
        StatesData<String, String> statesData = new StatesData<>(stateData);
        Collection<TransitionData<String, String>> transitionData = new ArrayList<>();
        transitionData.add(new TransitionData<String, String>("S1", "S2", "E1"));
        TransitionsData<String, String> transitionsData = new TransitionsData<>(transitionData);
        StateMachineModel<String, String> stateMachineModel = new DefaultStateMachineModel<String, String>(configurationData,
                statesData, transitionsData);
        return stateMachineModel;
    }

    @Override
    public StateMachineModel<String, String> build(String machineId) {
        return build();
    }
}

您可以轻松地从数据库动态加载状态和转换并填充 ConfigurationData