javaspringspring-statemachine

How do I configure more than 1 guard in a Spring Statemachine?


I have the following state machine configuration:

@Override
public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
    throws Exception {
transitions
        .withExternal()
        .source(States.S1).target(States.S2)
        .event(Events.E1)
        .guard(grd1())
        .and()
        .withExternal()
        .source(States.S2).target(States.S3)
        .event(Events.E2)
        .guard(grd2())
        .and()
        .withExternal()
        .source(States.S3).target(States.S4)
        .event(Events.E3)
        .guard(grd1())
        .guard(grd2());
}

For the last transition, I'd like both grd1 and grd2 to validate my transition. However, it seems that only one guard can be active at a time, using this code, only grd2 would execute, if I switched the order, only grd1 would execute.

Is there a way for both to run, without having to define a third guard which would have to be a combination of grd1 and grd2?


Solution

  • You can use this method:

    public static Guard<States, Events> lazyAndGuard(Guard<States, Events> guard1, Guard<States, Events> guard2) {
        return context -> guard1.evaluate(context) && guard2.evaluate(context);
    }
    

    and

    .guard(lazyAndGuard(grd1(), grd2()))