spring statemachine详解(-)
spring statemachine是spring的一个框架,即将状态机概念和spring相结合的一个框架。更详细的可以参考官网。
1.什么时候可以用spring statemachine
当你的项目有一个明显的状态流转的总流程时,你就可以使用这个框架。直白点,你在系统里下单,整个订单流程如下:待支付---支付--》待发货--发货-》待收货--收货--》订单完成,这个框架当你操作某个事件后,它会自动跳到下个状态。
2.如何使用statemachine
引入jar包
<dependency> <groupId>org.springframework.statemachine</groupId> <artifactId>spring-statemachine-starter</artifactId> <version>${spring.statemachine.version}</version> </dependency>
定义事件和状态
//定义事件 public enum Events { E1, E2 } //定义状态 public enum States { SI, S1, S2 } @Configuration @EnableStateMachine public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> { @Override public void configure(StateMachineConfigurationConfigurer<States, Events> config) throws Exception { config .withConfiguration() .autoStartup(true) .listener(listener()); } //配置状态机初始状态 @Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { states .withStates() .initial(States.SI) .states(EnumSet.allOf(States.class)); } /** * 配置状态流转 * @param transitions * @throws Exception */ @Override public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception { transitions .withExternal() .source(States.SI).target(States.S1).event(Events.E1) //SI->S1 经过事件E1 .and() .withExternal() .source(States.S1).target(States.S2).event(Events.E2) //S1->S2 经过事件E2 ; } //配置监听器 @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()); } }; } }
配置测试状态机功能
@SpringBootApplication public class StatemachineDemoApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(StatemachineDemoApplication.class, args); } @Autowired private StateMachine<States, Events> stateMachine; @Override public void run(String... args) throws Exception { System.out.println("开始状态改变:当前状态"+stateMachine.getState().getId()); stateMachine.sendEvent(Events.E1); System.out.println("当前状态:"+stateMachine.getState().getId()); stateMachine.sendEvent(Events.E2); System.out.println("第二次状态改变:"+stateMachine.getState().getId()); } }
观察打印结果。