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 甚至直接参与的机会。文档

相关文章
相关标签/搜索