【问题标题】:How to share instances between Prototypes (Spring LoC)如何在原型之间共享实例(Spring LoC)
【发布时间】:2023-03-27 08:42:01
【问题描述】:

要在TaskExecutor 中运行作业,我需要实例化实现Runnable 接口的新作业。为了解决这个问题,我会create a new Spring Prototype Bean named Job "on Demand"

但在我的应用程序中,Job 有两个字段 LocationChangerQueryTyper。这两个应该共享由WebDriverFactory 创建的同一个WebDriver 实例

现在的问题是如何使用 Spring 进行设计?

这是相关代码:

@Component
@Scope("prototype")
public class Job implements Runnable {

    @Autowired
    LocationChanger locationChanger;

    @Autowired
    QueryTyper queryTyper;

    @Override
    public void run() {
        // at this point the locationChanger and
        // queryTyper should share the same instance
    }

}

@Component
@Scope("prototype")
public class LocationChanger {

    @Autowired
    @Qualifier(...) // For every new Job Created, the same WebDriver instance should be injected.
    WebDriver webDriver
}

@Component
@Scope("prototype")
public class QueryTyper {

    @Autowired
    @Qualifier(...) // For every new Job Created, the same WebDriver instance should be injected.
    WebDriver webDriver
}

public class WebDriverFactoryBean implements FactoryBean<WebDriver> {
    @Override
    public WebDriver getObject() throws Exception {
        return // createdAndPrepare...
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

非常感谢!

更新 1: 一个可能的解决方案是在 Job only 中自动连接 WebDriver,然后在 @PostConstruct 中将此 WebDriver 注入到 LocationChangerQueryTyper。但后来我用手接线。

@Component
@Scope("prototype")
public class Job implements Runnable {

    @Autowired
    LocationChanger locationChanger;

    @Autowired
    QueryTyper queryTyper;

    @Autowired
    WebDriver webDriver;

    @PostConstruct
    public void autowireByHand() {
        locationChanger.setWebDriver(this.webDriver);
        queryTyper.setWebDriver(this.webDriver);
    }
}

// + remove all @Autowired WebDriver's from LocationChanger and QueryTyper

【问题讨论】:

  • 所以你想让WebDriver 成为单身人士?
  • 不,每次如果Job 被实例化,这个Job 和它的孩子应该共享相同的WebDriver。所以它不是单例:(

标签: java spring spring-ioc


【解决方案1】:

如果我理解您的要求,您需要在 JobLocationChanger 之间共享 WebDriver。所以它不是prototype 范围,也不是singleton 范围。为了解决这个问题,我认为您要么必须按照您的建议手动完成,要么您可以尝试实现自己的范围,如Spring reference documentation 中所述

编辑

顺便说一句,我认为您的“手动接线”解决方案看起来并不那么糟糕。

【讨论】:

  • 感谢自定义范围的想法。也许这就是道。我想到了动态限定符。例如:LocationChangerQueryTyper 应该像这样标记 Webdriver:@Autowire @Qualifier(Somehow Relate this String to the created Instance of Job) webDriver 注释。
  • 自定义范围应该是可能的。您只需要弄清楚将实例存储在何处以进行检索,然后将它们与“对话 id”相关联。
猜你喜欢
  • 2013-05-30
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-19
相关资源
最近更新 更多