Spring Statemachine中如何配置多个同时生效的过渡守卫?
Spring State Machine 多守卫生效问题解决
问题描述
我在配置状态机过渡时,给最后一个从States.S3到States.S4的过渡添加了两个守卫grd1和grd2,但发现多次调用.guard()方法时,只有最后一个守卫会生效,调换顺序则只有第一个生效,想让两个守卫都执行验证,且不想额外定义整合两者的第三个守卫。
原配置代码:
@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()); }
解决方法
Spring State Machine的guard()方法是覆盖式设置,每次调用都会替换之前设置的守卫。要添加多个守卫,需要使用复数形式的guards()方法,它支持传入多个Guard实例,所有传入的守卫都会被执行,且只有当所有守卫都返回true时,过渡才会触发。
修改后的代码
@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) .guards(grd1(), grd2()); // 改用guards方法传入多个守卫 }
这样修改后,grd1和grd2都会被执行,只有两者都验证通过,S3到S4的过渡才会发生。
内容的提问来源于stack exchange,提问作者user2308001
相关产品推荐
相关产品推荐

