1、编程式
下面以官网的示例稍加改造举例来体会一下Spring Statemachine使用。
添加下面maven坐标到pom中。
<dependencies>
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-core</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<!-- 对应spring-statemachine-core 2.1.3.RELEASE -->
<version>5.1.5.RELEASE</version>
</dependency>
</dependencies>
下面的示例说明如何配置和使用statemachine。假设我们有状态STATE1,STATE2和事件EVENT1,EVENT2。
enum States {
STATE1, STATE2
}
enum Events {
EVENT1, EVENT2
}
public static StateMachine<States, Events> buildMachine() throws Exception {
StateMachineBuilder.Builder<States, Events> builder = StateMachineBuilder.builder();
//设置状态机初始状态为STATE1、共有EnumSet.allOf(States.class)种状态
builder.configureStates()
.withStates()
.initial(States.STATE1)
.states(EnumSet.allOf(States.class));
//设置状态转移 原始状态STATE1触发EVENT1事件状态转移为STATE2、原始状态STATE2触发EVENT2事件状态转移为STATE1
builder.configureTransitions()
.withExternal()
.source(States.STATE1).target(States.STATE2)
.event(Events.EVENT1)
.and()
.withExternal()
.source(States.STATE2).target(States.STATE1)
.event(Events.EVENT2);
//配置状态机监听器,可监听多种事件、具体看接口StateMachineListener方法
builder.configureConfiguration()
.withConfiguration()
.listener(new StateMachineListenerAdapter<States, Events>() {
/**
* 状态变更后调用此方法
*/
@Override
public void stateChanged(State<States, Events> from, State<States, Events> to) {
System.out.println("State change to " + to.getId());
}
});
return builder.build();
}
public static void main(String[] args) throws Exception {
//构建状态机对象
StateMachine<States, Events> stateMachine = buildMachine();
//初始状态为STATE1、触发stateChanged方法打印State change to STATE1
stateMachine.start();
//打印State change to STATE2
stateMachine.sendEvent(Events.EVENT1);
//打印State change to STATE1
stateMachine.sendEvent(Events.EVENT2);
}
执行结果:
2、java类配置式
public class JavaConfigExample {
static enum States {
STATE1, STATE2
}
static enum Events {
EVENT1, EVENT2
}
@Configuration
@EnableStateMachine
static class Config1 extends EnumStateMachineConfigurerAdapter<States, Events> {
@Override
public void configure(StateMachineStateConfigurer<States, Events> states)
throws Exception {
states
.withStates()
.initial(States.STATE1)
.states(EnumSet.allOf(States.class));
}
@Override
public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
throws Exception {
transitions
.withExternal()
.source(States.STATE1).target(States.STATE2)
.event(Events.EVENT1)
.and()
.withExternal()
.source(States.STATE2).target(States.STATE1)
.event(Events.EVENT2);
}
}
@WithStateMachine
static class MyBean {
@OnTransition(target = "STATE1")
void toState1() {
}
@OnTransition(target = "STATE2")
void toState2() {
}
}
static class MyApp {
@Autowired
StateMachine<States, Events> stateMachine;
void doSignals() {
stateMachine.start();
stateMachine.sendEvent(Events.EVENT1);
stateMachine.sendEvent(Events.EVENT2);
}
}
}