0
我們有一個對象,它在彈簧引導容器中進行一些計算。讓我們稱之爲「表」。我們需要實例化 - 比如在應用程序啓動時使用10張紙。每次我們開始計算時,我們都需要通過DI訪問該表的一個實例,以便在額外的線程中運行。Spring依賴注入對象池
任何想法,如果這是可能的春季?
我們有一個對象,它在彈簧引導容器中進行一些計算。讓我們稱之爲「表」。我們需要實例化 - 比如在應用程序啓動時使用10張紙。每次我們開始計算時,我們都需要通過DI訪問該表的一個實例,以便在額外的線程中運行。Spring依賴注入對象池
任何想法,如果這是可能的春季?
您可以通過以下方式實現此目的。假設您有一個Sheet
類,如下所示。我用java8來編譯代碼。
Sheet.java
@Component("sheet")
@Scope(value = "prototype")
public class Sheet {
// Implementation goes here
}
現在你需要一個第二類SheetPool
持有的Sheet
10個實例SheetPool.java
public class SheetPool {
private List<Sheet> sheets;
public List<Sheet> getSheets() {
return sheets;
}
public Sheet getObject() {
int index = ThreadLocalRandom.current().nextInt(sheets.size());
return sheets.get(index);
}
}
注意SheetPool
不一個Spring組件。它只是一個普通的java類。
現在需要第三類是配置類,這將需要與Sheet
10實例創建SpringPool
對象ApplicationConfig.java
@Configuration
public class ApplicationConfig {
@Autowired
ApplicationContext applicationContext;
@Bean
public SheetPool sheetPool() {
SheetPool pool = new SheetPool();
IntStream.range(0, 10).forEach(e -> {
pool.getSheets().add((Sheet) applicationContext.getBean("sheet"));
});
return pool;
}
}
的護理現在當應用程序啓動SheetPool
對象時將創建具有10個不同的工作表實例。要訪問Sheet
對象使用下面的代碼。
@Autowired
SheetPool sheetPool;
Sheet sheetObj = sheetPool.getObject();
難道你不能使用一些常用的池嗎?像https://commons.apache.org/proper/commons-pool/? – 2017-06-06 05:39:16
創建自定義spring bean https://stackoverflow.com/a/15773000/6743203 –