new無语 转载请注明原创出处,谢谢!
本节只记录基本的MAVEN配置,和基础的配置使用。
maven依赖
<properties>
<spring-statemachine.version>2.0.1.RELEASE</spring-statemachine.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-bom</artifactId>
<version>${spring-statemachine.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
状态定义:
public enum States {
SI, S1, S2
}
事件定义
public enum Events {
E1, E2
}
状态机配置
@Configuration
@EnableStateMachine
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> {
@Override
public void configure(StateMachineConfigurationConfigurer<States, Events> config)
throws Exception {
config
.withConfiguration()
//指定自动启动状态机,默认为false
.autoStartup(true)
//状态监听
.listener(listener());
}
@Override
public void configure(StateMachineStateConfigurer<States, Events> states)
throws Exception {
states
.withStates()
//设置默认(初始化)状态
.initial(States.SI)
//指定状态ENUM
.states(EnumSet.allOf(States.class));
}
@Override
public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
throws Exception {
transitions
.withExternal()
//指定源状态->目标状态,and 触发事件
.source(States.SI).target(States.S1).event(Events.E1)
.and()
.withExternal()
.source(States.S1).target(States.S2).event(Events.E2);
}
/**
* 状态监听
*
* @return
*/
@Bean
public StateMachineListener<States, Events> listener() {
return new StateMachineListenerAdapter<States, Events>() {
@Override
public void stateChanged(State<States, Events> from, State<States, Events> to) {
System.out.println("State change to " + to.getId());
}
};
}
}
一个简单的FSM就配置好了,接下来test测试一下
@RunWith(SpringRunner.class)
@SpringBootTest
public class ZeePluginFsmApplicationTests {
@Autowired
private StateMachine<States, Events> stateMachine;
@Test
public void contextLoads() {
stateMachine.sendEvent(Events.E1);
stateMachine.sendEvent(Events.E2);
}
}
State change to SI
State change to S1
State change to S2
很显然,很简单的就完成的一个状态修改的过程。初始状态->S1状态->S2状态。
网友评论