Search code examples
javaspringspring-statemachine

Spring state machine annotation @WithStateMachine not working


I just encounter a problem when using spring state machine @WithStateMachine.

@WithStateMachine just work when I use it on inner class which defined in the class annotated by @EnableStateMachine, but when I define class in other place it seems not work. Here is my code:

@Configuration@EnableStateMachine public class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> {
@Override
public void configure(StateMachineStateConfigurer<States, Events> states)
    throws Exception {
    states
        .withStates()
        .initial(States.UNPAID)
        .states(EnumSet.allOf(States.class));
}

@Override
public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
    throws Exception {
    transitions
        .withExternal()
        .source(States.UNPAID).target(States.WAITING_FOR_RECEIVE)
        .event(Events.PAY)
        .and()
        .withExternal()
        .source(States.WAITING_FOR_RECEIVE).target(States.DONE)
        .event(Events.RECEIVE);
}

@Override
public void configure(StateMachineConfigurationConfigurer<States, Events> config)
    throws Exception {
    config
        .withConfiguration()
        .autoStartup(true);
}

@WithStateMachine
public class Action {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @OnTransition(target = "UNPAID")
    public void create() {
        logger.info("UNPAID");
    }

    @OnTransition(source = "UNPAID", target = "WAITING_FOR_RECEIVE")
    public void pay() {
        logger.info("WAITING_FOR_RECEIVE");
    }

    @OnTransition(source = "WAITING_FOR_RECEIVE", target = "DONE")
    public void receive() {
        logger.info("DONE");
    }
}}

but when I define Action in another class file, it is not work

enter image description here

my pom

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>1.2.3.RELEASE</version>
        </dependency><dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

Solution

  • @WithStateMachine is a meta-annotation having spring @Component. Check that your Action class is either component scanned or created manually as @Bean.

    Then it exist in application context and statemachine can find it.