java - spring-boot怎樣優雅得插入一個后臺線程?
問題描述
我有一個守護,可它需要插入數據到數據庫.不知道怎樣注入Bean服務,所以目前是這樣的:
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又開機運行在一個獨立線程里呢?
問題解答
回答1:不好意思各位,我自己找到方法了.:http://stackoverflow.com/ques...
根據回答的方法.改為@Componentclass ThreadRun implements DisposableBean.....然后在構造里啟動線程,destroy里關閉線程,而且能用到自動注入
回答2:你的意思是想進行接口的bean自動注入吧? 你可以參考spring關于抽象類的bean或接口對象的注入創建一個抽象類DataService implements Runnable 進行注入。然后extend它。因為springbean 的生命周期是在beanFactory創建的時候就創建完成,你的對象是創建的時候才進行對象需要注入,這點與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:這個線程是做什么用的?
相關文章:
1. mysql日期類型默認值’0000-00-00’ 報錯2. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?3. mysql replace 死鎖4. mysql - C#連接數據庫時一直這一句出問題int i = cmd.ExecuteNonQuery();5. MYSQL 根據兩個字段值查詢 但兩個值的位置可能是互換的,這個怎么查?6. extra沒有加載出來7. android - 安卓做前端,PHP做后臺服務器 有什么需要注意的?8. javascript - 微信網頁開發從菜單進入頁面后,按返回鍵沒有關閉瀏覽器而是刷新當前頁面,求解決?9. php傳對應的id值為什么傳不了啊有木有大神會的看我下方截圖10. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?
