Spring-Statemachine 状态机简单示例

最近学习状态机、看了很多、最多的就是这个入门简单示例

状态

public enum States {
    UNPAID,                 // 待支付
    WAITING_FOR_RECEIVE,    // 待收货
    DONE                    // 结束
}

事件

public enum Events {
    PAY,        // 支付
    RECEIVE     // 收货
}

状态机配置

@Configuration
@EnableStateMachineFactory(name = "orderStateMachine")
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public static final String orderStateMachineId = "orderStateMachineId";

    @Override
    public void configure(StateMachineStateConfigurer states) throws Exception {
        states
                .withStates()
                .initial(States.UNPAID)                //初始状态 定义了初始状态为待支付UNPAID,
                .states(EnumSet.allOf(States.class));  //则指定了使用上一步中定义的所有状态作为该状态机的状态定义。
    }

    @Override
    public void configure(StateMachineTransitionConfigurer transitions) throws Exception {
        transitions
                .withExternal()
                .source(States.UNPAID).target(States.WAITING_FOR_RECEIVE)// 指定状态来源和目标
                .event(Events.PAY)
                .action(enterAction())// 指定触发事件
                .guard(guard())
                .and()
                .withExternal()
                .source(States.WAITING_FOR_RECEIVE).target(States.DONE)
                .event(Events.RECEIVE);
    }

    @Bean
    public EnterAction enterAction() {
        return new EnterAction();
    }

    public class EnterAction implements Action {

        @Override
        public void execute(StateContext context) {
            logger.info("订单创建,进入时的行为");
        }
    }

    @Bean
    public Guard guard() {
        return new Guard() {

            @Override
            public boolean evaluate(StateContext context) {
                return true;
            }
        };
    }
}

注解监听器

@WithStateMachine(name = "orderStateMachineId")
public class EventConfig {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @OnTransition(target = "UNPAID")
    public void create() {
        logger.info("订单创建,待支付");
    }

    @OnTransition(source = "UNPAID", target = "WAITING_FOR_RECEIVE")
    public void pay() {
        logger.info("用户完成支付,待收货");
    }

    @OnTransition(source = "WAITING_FOR_RECEIVE", target = "DONE")
    public void receive() {
        logger.info("用户已收货,订单完成");
    }
}

Controller

@RestController
public class OrderController {
    @Resource(name = "orderStateMachine")
    private StateMachineFactory stateMachineFactory;

    @RequestMapping(value = "createOrder")
    public void createOrder(){
        StateMachine stateMachine =  stateMachineFactory.getStateMachine("orderStateMachineId");
        stateMachine.start();
        stateMachine.sendEvent(Events.PAY);
        stateMachine.sendEvent(Events.RECEIVE);
    }
}

文章仅作为个人学习整理

你可能感兴趣的:(Spring,状态机示例)