Spring StateMachine - Configure from Database

て烟熏妆下的殇ゞ 提交于 2019-12-04 20:52:24

Yes it is possible through a custom implementation of StateMachineModelFactory. You can hook it using StateMachineModelConfigurer like so:

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

In your implementation you can dynamically load whatever is needed for the SM model from external services. Below is an example from the 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();
    }
}

You can easily load the states and transitions dynamically from the DB and populate the ConfigurationData.

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