将存储库或服务注入Spring状态机Action and Guard的正确方法

问题描述

我一直在进入Spring Statemachine并使用它对Order状态进行建模。我读到有关console.log(event,reactNode)Guards的信息,并根据我们的要求提出了一个问题。

将Spring Actions@Repository注入@ServiceGuard的正确方法是什么?

the docs中所述,ActionGuard通过声明Action进行配置,但是我看不到注入@Bean@Service这样。

例如,以这个@Repository为例:

EnumStateMachineConfigurerAdapter

顶部@Configuration @EnableStateMachineFactory public class OrderStateMachineConfiguration extends EnumStateMachineConfigurerAdapter<OrderStates,OrderEvents> { @Override public void configure(StateMachinestateConfigurer<OrderStates,OrderEvents> states) throws Exception { states .withStates() .initial(OrderStates.PENDING) .initial(OrderStates.APPROVED) .initial(OrderStates.PAYMENT_REJECTED) .end(OrderStates.DELIVERED) .end(OrderStates.CANCELLED) .end(OrderStates.INVALID) .end(OrderStates.refundED) .end(OrderStates.ARCHIVED) .states(EnumSet.allOf(OrderStates.class)); } @Override public void configure(StateMachineConfigurationConfigurer<OrderStates,OrderEvents> config) throws Exception { config .withConfiguration() .listener(new StateMachineListener()); } @Override public void configure(StateMachineTransitionConfigurer<OrderStates,OrderEvents> transitions) throws Exception { transitions .withExternal().source(OrderStates.PENDING).target(OrderStates.APPROVED).event(OrderEvents.APPROVE).and() ... more transitions } @Bean public Guard<OrderStates,OrderEvents> orderIsConsistent() { return ctx -> { Order order = ctx.getExtendedState().get(ORDER_KEY,Order.class); return order.getInconsistencies().isEmpty(); }; } } 服务似乎是不正确的,因为这是@Autowired类,更不用说循环引用的风险了。

我想到的另一种解决方案可能是在创建状态机时将所需的服务注入@Configuration或状态机头中,然后通过extendedState访问它?

我希望能对此提供一些见解,因为我在文档中找不到答案。

解决方法

您可以在方法级别上注入依赖项:

@Bean
@Autowired
public Guard<OrderStates,OrderEvents> orderIsConsistent(OrderService orderService) {
    return ctx -> {
        Long orderId = ctx.getExtendedState().get(ORDER_ID,Long.class);
        Order order = orderService.findById(orderId);
        return order.getInconsistencies().isEmpty();
    };
}