【发布时间】:2023-03-27 08:42:01
【问题描述】:
要在TaskExecutor 中运行作业,我需要实例化实现Runnable 接口的新作业。为了解决这个问题,我会create a new Spring Prototype Bean named Job "on Demand"。
但在我的应用程序中,Job 有两个字段 LocationChanger 和 QueryTyper。这两个应该共享由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 注入到 LocationChanger 和 QueryTyper。但后来我用手接线。
@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