7

我正在尝试在我的项目中使用 Spring State Machine,因为有一个对象Order具有多个状态

  • 新的
  • 有薪酬的
  • 包装好的
  • 发表
  • 取消
  • 回来

该对象可以实现如下

public class Order {
  private String id;
  private Customer customer;
  private OrderState state;
// Some other fields with getter and setter
}

我引入了OrderService,从DB获取订单,设置一些信息,包括OrderState,然后保存到DB。

但是我不知道如何将 Spring 状态机应用到这个状态机中,使用这样的简单目的是否太复杂了?

4

1 回答 1

9

定义你的状态

public enum OrederStates {
   NEW, PAID, PACKAGED; // etc
}

然后定义你的事件

public enum OrderEvents {
    PAYMENT, PACK, DELIVER; // etc 
}

然后声明你的事件监听器

@WithStateMachine
public class OrderEventHandler {
    @Autowired
    OrderService orderService;

    @OnTransition(src= "NEW",target = "PAID")
    handlePayment() {
       // Your code orderService.*
       // ..   
    }
    // Other handlers
}

现在将您的应用程序配置为使用状态机

@Configuration
@EnableStateMachine
static class Config1 extends EnumStateMachineConfigurerAdapter<States, Events> {

    @Override
    public void configure(StateMachineStateConfigurer<States, Events> states)
            throws Exception {
        states
            .withStates()
                .initial(OrderStates.NEW)
                .states(EnumSet.allOf(OrderStates.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
            throws Exception {
        transitions
            .withExternal()
                .source(OrderStates.NEW).target(OrderStates.PAID)
                .event(OrderEvents.PAYMENT)
                .and()
            .withExternal()
                .source(OrderStates.PAID).target(OrderStates.PACKED)
                .event(OrderEvents.PACK);
    }
}

最后在您的应用程序/控制器中使用它

public class MyApp {

    @Autowired
    StateMachine<States, Events> stateMachine;

    void doSignals() {
        stateMachine.start();
        stateMachine.sendEvent(OrderEvents.PAYMENT);
        stateMachine.sendEvent(Events.PACK);
    }
 }

使用本指南开始使用状态机,并使用本参考资料了解更多信息。

于 2016-03-10T10:14:06.273 回答