Spring Statemachine Construct Statemachine
原创
©著作权归作者所有:来自51CTO博客作者陈振阳Plus的原创作品,请联系作者获取转载授权,否则将追究法律责任
StateMachineModel
这里的Model跟MVC模式里的Model是一个意义,是数据模型的意思;在Spring StateMachine内部,各种形式的状态及的配置首先被转换为StateMachineModel模块的表示;
Spring Statemachine使用StateMachineModel蚩尤的信息,构建Statemachine对象;
StateMachineModel->StateMachine的逻辑可以在StateMachineFactory接口的抽象实现AbstractStateMachineFactory中了解到具体细节。
Spring Statemachine提供了4中提供状态及配置的方式
- Java configuration
- UML(UmlStateMachineModelFactory)
- A repository(RepositoryStateMachineModelFactory,spring-statemachine-data-jpa,spring-statemachine-data-redis,spring-statemachine-data-mongodb)
- custom StateMachineModel,前三中方式提供的配置信息最终都会转换为StateMachineModel
A machine can be built from Java configuration, UML, or a repository. If you want to go crazy, you can also use a custom StateMachineModel, which is the lowest possible level at which to define configuration.
Spring Statemachine中还有一个persist模块,persist是用来持久花StateMachineContext对象的,也就是persist持久花的是一个Statemachine的运行时信息;上面提到的repository是持久花的配置信息。
Spring Statemachine从repository读取配置信息,构建StatemachineModel配置模型,StatemachineFactory蚩尤StateMachineModelFactory对象的引用,通过StatemachineModel提供的信息构建Statemachine,Statemachine的运行时信息可以通过persist模块持久花到对应的存储,Spring Statemachine默认提供了redis,jpa和mangodb三种持久花方式;
Spring Statemachine提供的data模块同时提供了Statemachine配置信息和运行时信息的持久花能力
spring-statemachine-data-common
spring-statemachine-data-jpa
spring-statemachine-data-redis
spring-statemachine-data-mongodb
StateMachineBuilder
public static StateMachine<String, String> buildMachine(BeanFactory beanFactory) throws Exception {
Builder<String, String> builder = StateMachineBuilder.builder();
builder.configureConfiguration()
.withConfiguration()
.machineId("myMachineId")
.beanFactory(beanFactory);
builder.configureStates()
.withStates()
.initial("S1")
.state("S2");
builder.configureTransitions()
.withExternal()
.source("S1")
.target("S2")
.event("E1");
return builder.build();
}
Custom StateMachineModel
// setup configuration data
ConfigurationData<String, String> configurationData = new ConfigurationData<>();
// setup states data
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);
// setup transitions data
Collection<TransitionData<String, String>> transitionData = new ArrayList<>();
transitionData.add(new TransitionData<String, String>("S1", "S2", "E1"));
TransitionsData<String, String> transitionsData = new TransitionsData<>(transitionData);
// setup model
StateMachineModel<String, String> stateMachineModel = new DefaultStateMachineModel<>(configurationData, statesData,
transitionsData);
// instantiate machine via factory
ObjectStateMachineFactory<String, String> factory = new ObjectStateMachineFactory<>(stateMachineModel);
StateMachine<String, String> stateMachine = factory.getStateMachine();