[英]Spring boot. How to take advantage of the Prototype scope?
我試圖找到一種在Spring啟動中創建優美的Runnable bean的方法。 該應用程序的重點是提供一項服務,該服務將接收一些數據並啟動受監視的外部過程。
在之前的嘗試中,我只是形成了一個常規的new MyRunnable()
並將其傳遞給執行服務。 現在,我正在考慮如何使用Spring環境並使用@Scope("prototype")
來正確執行此操作。
我確實找到了使用ApplicationContext.getBean(...)
示例,以及為什么Spring的ApplicationContext.getBean被認為是不好的更好方法? ,但是我仍然無法正確地理解如何根據一項服務來實際調用new MyRunnable()
,這將遵循以下簡單思想:
class MyService {
public void triggerNewExternalTask() {
....
executionService.run(new MyRunnable());
我相信您在這里走錯了路。
Spring依賴項注入非常棒,但這並不意味着您永遠不會在正確編寫的Spring Boot應用程序中找到對new
的調用。
在這種情況下,調用new
是正確的事情。 池中的每個Executor
在啟動時都應獲得其自己的Runnable
/ Callable
實例。
這對於任何方法范圍的變量都是如此:最好在方法范圍內實例化它,並在退出方法時讓垃圾回收器將其清除。 在這種情況下,沒有理由讓Spring負責bean的生命周期。
你走得太遠,當您嘗試共享Runnable
情況下,特別是如果他們有狀態。
即使問題已經解決,也偶然發現了另一個解決方案-@Lookup,它可以滿足以下任務:實體:
@Component
@Scope("prototype")
public class Proto {
private static int counter;
public Proto() {
System.out.println("count: "+counter++);
}
}
服務:
@Service
public class ProtoService {
@Lookup
public Proto getProto() {
return null;
}
}
和測試:
@Service
public class LookupWorks {
@Autowired
private ProtoService serv;
@PostConstruct
private void test() {
System.out.println(">>>>>>>>>>>>>>");
serv.getProto();
serv.getProto();
serv.getProto();
serv.getProto();
serv.getProto();
System.out.println(">>>>>>>>>>>>>>");
}
}
輸出:
>>>>>>>>>>>>>>
count: 0
count: 1
count: 2
count: 3
count: 4
>>>>>>>>>>>>>>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.