Spring Statemachine 1.0 發佈

最近 Spring 家族又填新丁 —— Spring Statemachine,Spring 狀態機:java

Spring Statemachine 1.0.0 Released http://spring.io/blog/2015/10/13/spring-statemachine-1-0-0-releasedspring

Spring Statemachine Homepage http://projects.spring.io/spring-statemachine/框架

之因此介紹這個項目是由於狀態機是一個解決某些複雜邏輯的不錯的選擇。以前在作一個即時通訊項目的時候就大量使用了狀態機的設計。緣由也很簡單,就是系統中存在大量各式各樣的狀態,以及能使系統在這些狀態之間轉換的事件。採用狀態機的設計即是天然而然的事情。ide

可是當時咱們項目的狀態機實現並很差,複雜笨重。其中一個缺點是,狀態轉換的定義語法複雜,可讀性差。但無奈當時市面上並無太好的通用的狀態機框架可供使用。後來無心間發現了 Apache Mina 中的狀態機實現其實還不錯,用法簡單。因此後來就參考 Mina 實現了一個可用 Annotation 定義事件 Transaction 的狀態機實現,並用它改進項目中設計。固然後來由於換工做,這些改進就沒有繼續。編碼

固然,用 Annotation 定義狀態機流轉有一個很大的缺點是沒有一個統一的地方能夠定義狀態的轉換。若是項目實現發展,同時又缺少良好的編碼規範和文檔,那狀態轉換的這部分邏輯就變得難以跟蹤了。設計

Spring Statemachine 使用的是 DSL 和 Annotation 相結合的方式定義狀態轉換規則:code

狀態轉換定義:blog

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

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

    @Override
    public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
            throws Exception {
        transitions
            .withExternal()
                .source(States.STATE1).target(States.STATE2)
                .event(Events.EVENT1)
                .and()
            .withExternal()
                .source(States.STATE2).target(States.STATE1)
                .event(Events.EVENT2);
    }
}

狀態機:事件

@WithStateMachine
static class MyBean {

    @OnTransition(target = "STATE1")
    void toState1() {
    }

    @OnTransition(target = "STATE2")
    void toState2() {
    }
}

Spring Statemachine 設計的好壞目前還很差作判斷,由於目前我暫時沒有項目須要採用狀態機設計。若是各位有須要狀態機設計的能夠考慮採用 Spring Statemachine。並且這是一個新項目,若是深刻使用它會有不少機會提交 patch 甚至直接參與的機會。文檔

相關文章
相關標籤/搜索