Spring Statemachine简记-第一个Spring Statemachine应用程序(一)

new無语 转载请注明原创出处,谢谢!

本节只记录基本的MAVEN配置,和基础的配置使用。

maven依赖


        2.0.1.RELEASE
    

    
        
            org.springframework.statemachine
            spring-statemachine-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.statemachine
                spring-statemachine-bom
                ${spring-statemachine.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

状态定义:

public enum States {
    SI, S1, S2
}

事件定义

public enum Events {
    E1, E2
}

状态机配置

@Configuration
@EnableStateMachine
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter {

    @Override
    public void configure(StateMachineConfigurationConfigurer config)
            throws Exception {
        config
                .withConfiguration()
                //指定自动启动状态机,默认为false
                .autoStartup(true)
                //状态监听
                .listener(listener());
    }

    @Override
    public void configure(StateMachineStateConfigurer states)
            throws Exception {
        states
                .withStates()
                //设置默认(初始化)状态
                .initial(States.SI)
                //指定状态ENUM
                .states(EnumSet.allOf(States.class));
    }

    @Override
    public void configure(StateMachineTransitionConfigurer transitions)
            throws Exception {
        transitions
                .withExternal()
                //指定源状态->目标状态,and 触发事件
                .source(States.SI).target(States.S1).event(Events.E1)
                .and()
                .withExternal()
                .source(States.S1).target(States.S2).event(Events.E2);
    }

    /**
     * 状态监听
     *
     * @return
     */
    @Bean
    public StateMachineListener listener() {
        return new StateMachineListenerAdapter() {
            @Override
            public void stateChanged(State from, State to) {
                System.out.println("State change to " + to.getId());
            }
        };
    }

}

一个简单的FSM就配置好了,接下来test测试一下

@RunWith(SpringRunner.class)
@SpringBootTest
public class ZeePluginFsmApplicationTests {

    @Autowired
    private StateMachine stateMachine;

    @Test
    public void contextLoads() {
        stateMachine.sendEvent(Events.E1);
        stateMachine.sendEvent(Events.E2);
    }
}
State change to SI
State change to S1
State change to S2

很显然,很简单的就完成的一个状态修改的过程。初始状态->S1状态->S2状态。

你可能感兴趣的:(Spring Statemachine简记-第一个Spring Statemachine应用程序(一))