'Get StateContext in @OnTransition annotated method

In the Spring Statemachine reference doc is this sample code:

@WithStateMachine
static class Bean1 {

    @OnTransition(source = "S1", target = "S2")
    public void fromS1ToS2() {
    }
}

Is it possible to access the StateContext object from a method annotated with @OnTransition? Perhaps I don't understand the correct use of the annotation...I thought it could be used in a similar manner as an Action, where I could access data stored in the ExtendedState.



Solution 1:[1]

It seems that I've totally forget to add this specific information on our docs. We can't access StateContext but event headers and ExtendedState are available.

There's a unit test for this in MethodAnnotationTests.

Short story is that processor handling method calling detects argument types ExtendedState and Map if it's annotated with @EventHeaders. I've also been thinking to support StateContext in a same way via method arguments but haven't yet got that far.

@WithStateMachine
public class Bean2 {

  @OnTransition(source = "S1", target = "S2")
  public void method1(@EventHeaders Map<String, Object> headers, ExtendedState extendedState) {
  }

}

I'll also get docs sorted out for this, thx for pointing this out!

Solution 2:[2]

Their documentation says:

A method annotated with @OnTransition may accept a parameter of type ExtendedState, Map if map argument itself is annotated with EventHeaders, StateMachine, Message or Exception.

https://docs.spring.io/spring-statemachine/docs/current/api/org/springframework/statemachine/annotation/OnTransition.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Janne Valkealahti
Solution 2 nsv