Spring狀態機爲程序開發員提供了傳統狀態機和Spring應用程序使用,有如下特性:安全
/** * 狀態 */ public enum Status{ START, CANCEL, ENE; } /** * 事件 */ public enum Events { SAVE; }
@Configuration @EnableStateMachine(name = "orderStateMachine") public class TestStateMachineConfig extends EnumStateMachineConfigurerAdapter<Status, Events> { @Resource private SaveAction saveAction; @Override public void configure(StateMachineStateConfigurer<Status, Events> states) throws Exception { states .withStates() .initial(Status.START) .states(EnumSet.allOf(Status.class)); } @Override public void configure(StateMachineTransitionConfigurer<Status, Events> transitions) throws Exception { transitions .withExternal() .source(Status.START).target(Status.END) .event(Events.SAVE).action(saveAction) ; } @Override public void configure(StateMachineConfigurationConfigurer<Status, Events> config) throws Exception { config .withConfiguration().autoStartup(true) .listener(listener()); } @Bean public StateMachineListener<Status, Events> listener() { return new StateMachineListenerAdapter<Status, Events>() { @Override public void transition(Transition<Status, Events> transition) { if (transition.getTarget().getId() == Status.START) { System.out.println("建立"); return; } } }; } }
@Component public class SaveAction implements Action<Status, Events>{ @Resource private OrderInfoService orderInfoService; @Override public void execute(StateContext<Status, Events> context) { Order order = (Order) context.getMessageHeader(OrderStatusContextKey.ORDER_ENTITY_KEY); orderInfoService.save(order); } }
@Component public class DefaultStateMachineManager implements InitializingBean, ApplicationContextAware { private static final String ORDER_STATE_MACHINE_CONFIG = "orderStateMachine"; private ApplicationContext applicationContext; private StateMachine<Status, Events> orderStateMachine; @Override public void afterPropertiesSet() throws Exception { orderStateMachine = applicationContext.getBean(ORDER_STATE_MACHINE_CONFIG, StateMachine.class); } @Override public StateMachine<OrderStatus, Events> getOrderStateMachine() { return orderStateMachine; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
@Service public class OrderBizImpl { @Resource private StateMachineManager stateMachineManager; @Override public void save(Order order) { if (order == null) { return; } StateMachine<Status, Events> orderStateMachine = stateMachineManager.getOrderStateMachine(); Message<Events> message = MessageBuilder .withPayload(Events.SAVE) .setHeader(ORDER_ENTITY_KEY, order) .build(); orderStateMachine.sendEvent(message); } }