天天看點

Spring singleton bean 與 prototype bean 的依賴

我們知道,spring bean 預設的 scope 是 singleton(單例),但有些場景(比如多線程)需要每次調用都生成一個執行個體, 此時 scope 就應該設為 prototype。如:

但是,如果 singlton bean 依賴 prototype bean ,通過依賴注入方式, prototype bean 在 singlton bean 執行個體化時會建立一次(隻一次), 比如:

我希望排程“lily” 和 “lucy” 兩個線程,實際上,它隻給我初始化一個執行個體(這樣就線程非安全了)。

Spring singleton bean 與 prototype bean 的依賴

如果 singlton bean 想每次都去建立一個新的 prototype bean 的執行個體, 需要通過方法注入的方式。 可以通過實作 applicationcontextaware 接口,來擷取到 applicationcontext 執行個體, 繼而通過 getbean 方法來擷取到 prototype bean 的執行個體。我們的程式需要修改如下:

ok ,問題解決

Spring singleton bean 與 prototype bean 的依賴

<a href="https://github.com/waylau/spring-framework-4-reference">spring framework 4.x參考文檔</a>