Spring 状态机极简使用
本文不探讨状态机的思想与Spring状态机的架构,仅做快速实现参考。
Spring 状态机官方文档
项目参考代码
基于SpringBoot配置的快速集成案例
maven 依赖配置
| <dependency> |
| <groupId>org.springframework.statemachine</groupId> |
| <artifactId>spring-statemachine-starter</artifactId> |
| <version>4.0.0</version> |
| </dependency> |
java代码
| @Configuration |
| @EnableStateMachine |
| public class Config1Enums |
| extends EnumStateMachineConfigurerAdapter<States, Events> { |
| |
| @Override |
| public void configure(StateMachineStateConfigurer<States, Events> states) |
| throws Exception { |
| states |
| .withStates() |
| .initial(States.S1) |
| .end(States.SF) |
| .states(EnumSet.allOf(States.class)); |
| } |
| |
| } |
极简自定义集成案例
该案例支持每次以入参状态作为初始状态获取一个新的状态机。可作为最小接入代价状态机使用。
| |
| |
| |
| |
| |
| |
| |
| |
| @Slf4j |
| @RequiredArgsConstructor |
| @Component |
| public class SimpleStateMachineService { |
| |
| public StateMachine<States, Events> getStateMachine(States initStates) throws Exception { |
| |
| StateMachineBuilder.Builder<States, Events> builder = StateMachineBuilder.builder(); |
| builder.configureConfiguration() |
| .withConfiguration().autoStartup(true) |
| .and() |
| .withVerifier().enabled(true); |
| |
| builder.configureStates().withStates() |
| .initial(initStates) |
| .states(EnumSet.allOf(States.class)); |
| |
| builder.configureTransitions() |
| .withExternal() |
| .event(E1).source(S1).target(S2) |
| .guard(guard()) |
| .action(action()) |
| .and() |
| .withExternal() |
| .event(E2).source(S2).target(S0) |
| .guard(guard()) |
| .action(action()); |
| |
| return builder.build(); |
| |
| } |
| |
| private Guard<States, Events> guard() { |
| return stateModel -> { |
| Object data = stateModel.getMessageHeader("data"); |
| return Boolean.TRUE.equals(data); |
| }; |
| } |
| |
| private Action<States, Events> action() { |
| return context -> log.info("源状态:{},目标状态:{},事件:{}", context.getSource().getId(), context.getTarget().getId(), context.getEvent()); |
| } |
| } |
| `` |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-07-28 记录一次docker启动失败