簡體   English   中英

如何在原型之間共享實例(Spring LoC)

[英]How to share instances between Prototypes (Spring LoC)

要運行在一個工作TaskExecutor我需要執行實例化新的就業機會Runnable接口。 為了解決這個問題,我將創建一個新的Spring Prototype Bean,名為Job“ on Demand”

但是在我的應用程序中, Job有兩個字段LocationChangerQueryTyper 這兩個應該共享相同WebDriver通過創建的實例 WebDriverFactory

現在的問題是如何用Spring設計這個?

建築的UML

這是相關代碼:

@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注入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

如果我了解您的要求,則需要在JobLocationChanger之間共享WebDriver 因此,它不是prototype范圍,也不是singleton范圍。 為了解決這個問題,我認為您要么按照您的建議手工完成,要么嘗試實現自己的作用域,如Spring參考文檔中所述

編輯

我認為您的“手動”解決方案看起來並不糟糕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM