<dependency> <groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-core</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
public enum States {
INITIAL, STATE1, STATE2, FINAL
}
public enum Events {
EVENT1, EVENT2
}
@Configuration
@EnableStateMachine
public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> {
@Override
public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception {
states
.withStates()
.initial(States.INITIAL)
.states(EnumSet.allOf(States.class));
}
@Override
public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception {
transitions
.withExternal()
.source(States.INITIAL).target(States.STATE1).event(Events.EVENT1)
.and()
.withExternal()
.source(States.STATE1).target(States.STATE2).event(Events.EVENT2)
.and()
.withExternal()
.source(States.STATE2).target(States.FINAL);
}
}
@Service
public class StateMachineService {
@Autowired
private StateMachine<States, Events> stateMachine;
public void execute() {
stateMachine.start();
stateMachine.sendEvent(Events.EVENT1);
stateMachine.sendEvent(Events.EVENT2);
stateMachine.stop();
}
}