How to add spring state machine listener on entity creation?

515 Views Asked by At

I have working state machine transition listeners configured: an action is invoked when entity's state changes from A to B. Now I need to invoke an action when entity is created with initial state A. How could I do this?

@Override
public void configure(StateMachineStateConfigurer<State, Event> states) throws Exception {
    states.withStates().initial(State.A).states(EnumSet.allOf(State.class));
}

@Override
public void configure(StateMachineTransitionConfigurer<State, Event> transitions) throws Exception {
    transitions
    
      // this does not work
      .withExternal()
      .event(Event.CREATE).source(null).target(State.A)
      .action(action())
      //
      
      .and()
      .withExternal()
      .event(Event.COMPLETE).source(State.A).target(State.B)
      .action(action());
}

private Action<State, Event> action() {
    return stateContext -> {
        final Entity entity = (Entity) stateContext.getMessageHeader(ENTITY);
        log.info(entity.getState());
    };
}

....
enum StateMachineHeader {
  ENTITY
}
....
1

There are 1 best solutions below

7
On

The framework allows us to configure how actions are triggered in two ways. The usual is via transitions (where you show an example that does not work because it doesn't have a valid source. Another way is to configure entry/exit actions in the state configuration.

Can you try the configuration bellow to see if it satisfies your requirement?

@Override
public void configure(StateMachineStateConfigurer<State, Event> states) throws Exception {
    states.withStates().initial(State.A, action()).states(EnumSet.allOf(State.class));