【问题标题】:Spring State Machine - Why documentation use static classesSpring State Machine - 为什么文档使用静态类
【发布时间】:2020-01-20 12:59:50
【问题描述】:

Spring Statemachine 中,主要示例使用static 类作为@Configuration

@Configuration
@EnableStateMachine
static class Config1 extends EnumStateMachineConfigurerAdapter<States, Events> {

还有豆子

@WithStateMachine
static class MyBean {

同样使用@Autowired:

static class MyApp {
   @Autowired
   StateMachine<States, Events> stateMachine;

是可以忽略的旧文档/示例文档,还是有真正的理由/需要使用静态类?

【问题讨论】:

    标签: java spring static-classes spring-statemachine


    【解决方案1】:

    如果您使用注释@EnableStateMachine@EnableStateMachineFactory,它们不必是静态的。但是,如果您不使用这些注释并想要构建和配置它,则必须使用静态。

    @WithStateMachine 的所有功能都可以通过使用注解 @EnableWithStateMachine 来启用,该注解只需将所需的配置导入 Spring Application Context。 @EnableStateMachine 和 @EnableStateMachineFactory 都已经用这个注释了,所以用户不需要再次添加它。但是,如果机器是在不使用配置适配器的情况下构建和配置的,则必须使用 @EnableWithStateMachine 才能使用 @WithStateMachine 的功能。这个想法如下所示......

    查看此文档:StateMachine

    【讨论】:

    • @EnableStateMachine 也在静态类中,您的报价没有静态引用
    • 我想说的是它们不需要是静态的。有时必须动态创建状态机,如果在编译时使用静态定义,这是不可能实现的。
    【解决方案2】:

    是可以忽略的旧/示例文档还是有真实的 原因/需要使用静态类?

    是的。

    无需静态 - 查看附录中的最新示例 -> 快速示例 - https://docs.spring.io/spring-statemachine/docs/2.1.3.RELEASE/reference/#quick-example 甚至在预发布 3.0.0M1 中 - https://docs.spring.io/spring-statemachine/docs/3.0.0.M1/reference/#appendices

    【讨论】:

    • 谢谢,使用Spring DI的时候使用静态类有错吗?
    • 从问题的上下文来看,我假设您的意思是用 @Configuration 注释的静态类 - 请记住那些是内部(嵌套)类 - 这没有错。将同一组件的不同配置捆绑在一个类中并在单独的静态内部类中定义是一种常见模式(例如,对于组件 X - 静态配置 A(用于本地使用)和静态配置 B(用于产品使用)等。
    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多