习惯的力量是巨大的。——西塞罗

文档:

https://docs.spring.io/spring-statemachine/docs/current/reference/#state-machine-via-builder

此处表明状态机不仅可以通过配置类的方式进行配置,还可以通过建造者模式动态构建

1
2
3
4
5
6
7
8
9
StateMachine<String, String> buildMachine1() throws Exception {
Builder<String, String> builder = StateMachineBuilder.builder();
builder.configureStates()
.withStates()
.initial("S1")
.end("SF")
.states(new HashSet<String>(Arrays.asList("S1","S2","S3","S4")));
return builder.build();
}

这里声明了许多的states

还可以修改其配置

1
2
3
4
5
6
7
8
9
StateMachine<String, String> buildMachine2() throws Exception {
Builder<String, String> builder = StateMachineBuilder.builder();
builder.configureConfiguration()
.withConfiguration()
.autoStartup(false)
.beanFactory(null)
.listener(null);
return builder.build();
}

当然事件也可以定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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();
}

@WithStateMachine(id = "myMachineId")
static class Bean17 {

@OnStateChanged
public void onStateChanged() {
}
}