问题描述
我一直在进入Spring Statemachine并使用它对Order状态进行建模。我读到有关console.log(event,reactNode)
和Guards
的信息,并根据我们的要求提出了一个问题。
将Spring Actions
或@Repository
注入@Service
或Guard
的正确方法是什么?
如the docs中所述,Action
和Guard
通过声明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();
};
}