java - spring-boot怎樣優(yōu)雅得插入一個后臺線程?
問題描述
我有一個守護(hù),可它需要插入數(shù)據(jù)到數(shù)據(jù)庫.不知道怎樣注入Bean服務(wù),所以目前是這樣的:
public static void main(String[] args) { Thread daemon=new Thread(new DaemonRun()); daemon.setDaemon(true); daemon.start(); SpringApplication.run(Application.class, args); } ....public class DaemonRun implements Runnable { private DataService dataService; public synchronized DataService getDataService(){if(dataService==null)dataService=(DataService)SpringApplicationContextHolder.getSpringBean('dataService');return dataService; }
有沒有辦法讓DataService 自動注入DaemonRun同時DaemonRun又開機(jī)運行在一個獨立線程里呢?
問題解答
回答1:不好意思各位,我自己找到方法了.:http://stackoverflow.com/ques...
根據(jù)回答的方法.改為@Componentclass ThreadRun implements DisposableBean.....然后在構(gòu)造里啟動線程,destroy里關(guān)閉線程,而且能用到自動注入
回答2:你的意思是想進(jìn)行接口的bean自動注入吧? 你可以參考spring關(guān)于抽象類的bean或接口對象的注入創(chuàng)建一個抽象類DataService implements Runnable 進(jìn)行注入。然后extend它。因為springbean 的生命周期是在beanFactory創(chuàng)建的時候就創(chuàng)建完成,你的對象是創(chuàng)建的時候才進(jìn)行對象需要注入,這點與spring的概念沖突。
以下摘自stackoverflow,
Mark the abstract base class definition as abstract by using the abstract attribute , and in the concrete class definition , make the parent attribute be the name of the abstract class ’s bean nameSomething like this:<bean abstract='true' class='pacakge1.AbstractBaseClass'> <property name='mailserver' value='DefaultMailServer'/></bean><bean parent='abstractBaseClass'> <!--Override the value of the abstract based class if necessary--> <property name='mailserver' value='AnotherMailServer'/></bean>回答3:
使用自動注入,把scope配置成prototype試試吧。
回答4:這個線程是做什么用的?
相關(guān)文章:
1. javascript - node.js promise沒用2. golang - 用IDE看docker源碼時的小問題3. yii2中restful配置好后在nginx下報404錯誤4. 算法 - python 給定一個正整數(shù)a和一個包含任意個正整數(shù)的 列表 b,求所有<=a 的加法組合5. android 如何實現(xiàn)如圖中的鍵盤上的公式及edittext的內(nèi)容展示呢6. java - 我在用Struts2上傳文件時,報以下錯誤怎么回事?7. c++ - 如何正確的使用QWebEngineView?8. PHP注冊功能9. mysql - 求SQL語句10. MySQL如何實現(xiàn)表中再嵌套一個表?
