You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:22:09