[英]How to share instances between Prototypes (Spring LoC)
要運行在一個工作TaskExecutor
我需要執行實例化新的就業機會Runnable
接口。 為了解決這個問題,我將創建一個新的Spring Prototype Bean,名為Job“ on Demand” 。
但是在我的應用程序中, Job
有兩個字段LocationChanger
和QueryTyper
。 這兩個應該共享相同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
,然后在@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
如果我了解您的要求,則需要在Job
和LocationChanger
之間共享WebDriver
。 因此,它不是prototype
范圍,也不是singleton
范圍。 為了解決這個問題,我認為您要么按照您的建議手工完成,要么嘗試實現自己的作用域,如Spring參考文檔中所述
編輯
我認為您的“手動”解決方案看起來並不糟糕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.