要在其中运行作业,TaskExecutor
我需要实例化实现Runnable
接口的新作业。为了解决这个问题,我将创建一个名为 Job "on Demand" 的新 Spring Prototype Bean。
但是在我的应用程序中 aJob
有两个字段LocationChanger
和QueryTyper
. 这两个应该共享由 a 创建的同一个WebDriver
实例WebDriverFactory
。
现在的问题是如何用 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:
一种可能的解决方案可能是仅WebDriver
在 Job中自动装配,然后将此 WebDriver 注入到and中。但后来我用手接线。@PostConstruct
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