提前准备
jar包:gradle
dependencies {
compile(
"org.springframework.boot:spring-boot-starter-web:${springBootVersion}",
"org.springframework.statemachine:spring-statemachine-core:1.2.0.RELEASE",
)
}
先定义state
state 就是程序中某事物运行时的各种状态
public enum States {
ADD,
MODIFY,
CANCEL
}
再定义触发事件
event :改变状态的触发事件
public enum Events {
PICK_UP,
GIVE_UP,
DROP
}
配置stateConfig
配置事件event、状态state的关系
@Configuration
@EnableStateMachine
public class StatesConfig extends EnumStateMachineConfigurerAdapter<States, Events> {
@Override
public void configure(StateMachineStateConfigurer<States, Events> Statess) throws Exception {
Statess.withStates()
.initial(States.ADD)
.states(EnumSet.allOf(States.class));
}
//
@Override
public void configure(StateMachineConfigurationConfigurer<States, Events> config)
throws Exception {
config
.withConfiguration()
.autoStartup(true)
.listener(listener());
}
@Override
public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception {
transitions
.withExternal()
.source(States.ADD)
.target(States.MODIFY)
.event(Events.PICK_UP)
.and()
.withExternal()
.source(States.ADD)
.target(States.CANCEL)
.event(Events.DROP)
.and()
.withExternal()
.source(States.MODIFY)
.target(States.CANCEL)
.event(Events.GIVE_UP);
}
@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.getId());
}
};
}
}
触发事件
@Component
public class EventSend implements CommandLineRunner {
@Autowired
StateMachine<States, Events> stateMachine;
//发送事件
@Override
public void run(String... args) throws Exception {
stateMachine.start();
stateMachine.sendEvent(Events.PICK_UP);
stateMachine.sendEvent(Events.GIVE_UP);
stateMachine.sendEvent(Events.DROP);
}
}
使用spring boot 启动项目
@SpringBootApplication
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
期望输出结果:
state change ... ADD
state change ... MODIFY
state change ... CANCEL