一 点睛
Spring StateMachine框架可能对于大部分使用Spring的开发者来说还比较生僻,它的主要功能是帮助开发者简化状态机的开发过程,让状态机结构更加层次化。它的第三个Release版本1.2.0,其中增加了对Spring Boot的自动化配置。
我们通过一个简单的示例来对Spring StateMachine有一个初步的认识。
假设我们需要实现一个订单的相关流程,其中包括订单创建、订单支付、订单收货三个动作。
二 实战
1 新建pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-core</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
</dependencies>
2 定义状态和事件枚举
/*
其中共有三个状态(待支付、待收货、结束)以及两个引起状态迁移的事件(支付、收货)。
支付事件PAY会触发状态从待支付UNPAID状态到待收货WAITING_FOR_RECEIVE状态的迁移,
收货事件RECEIVE会触发状态从待收货WAITING_FOR_RECEIVE状态到结束DONE状态的迁移。
*/
public enum States {
UNPAID, // 待支付
WAITING_FOR_RECEIVE, // 待收货
DONE // 结束
}
public enum Events {
PAY, // 支付
RECEIVE // 收货
}
3 创建状态机配置类
package com.didispace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.b