java - spring-boot怎樣優(yōu)雅得插入一個(gè)后臺(tái)線(xiàn)程?
問(wèn)題描述
我有一個(gè)守護(hù),可它需要插入數(shù)據(jù)到數(shù)據(jù)庫(kù).不知道怎樣注入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; }
有沒(méi)有辦法讓DataService 自動(dòng)注入DaemonRun同時(shí)DaemonRun又開(kāi)機(jī)運(yùn)行在一個(gè)獨(dú)立線(xiàn)程里呢?
問(wèn)題解答
回答1:不好意思各位,我自己找到方法了.:http://stackoverflow.com/ques...
根據(jù)回答的方法.改為@Componentclass ThreadRun implements DisposableBean.....然后在構(gòu)造里啟動(dòng)線(xiàn)程,destroy里關(guān)閉線(xiàn)程,而且能用到自動(dòng)注入
回答2:你的意思是想進(jìn)行接口的bean自動(dòng)注入吧? 你可以參考spring關(guān)于抽象類(lèi)的bean或接口對(duì)象的注入創(chuàng)建一個(gè)抽象類(lèi)DataService implements Runnable 進(jìn)行注入。然后extend它。因?yàn)閟pringbean 的生命周期是在beanFactory創(chuàng)建的時(shí)候就創(chuàng)建完成,你的對(duì)象是創(chuàng)建的時(shí)候才進(jìn)行對(duì)象需要注入,這點(diǎ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:
使用自動(dòng)注入,把scope配置成prototype試試吧。
回答4:這個(gè)線(xiàn)程是做什么用的?
相關(guān)文章:
1. javascript - sublime快鍵鍵問(wèn)題2. javascript - immutable配合react提升性能?3. css - 寫(xiě)頁(yè)面遇到個(gè)布局問(wèn)題,求大佬們幫解答,在線(xiàn)等,急!~4. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問(wèn)5. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問(wèn)?6. 實(shí)現(xiàn)bing搜索工具urlAPI提交7. 配置Apache時(shí),添加對(duì)PHP的支持時(shí)語(yǔ)法錯(cuò)誤8. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽(tīng)數(shù)據(jù)變化9. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?10. phpstudy8.1支持win11系統(tǒng)嗎?

網(wǎng)公網(wǎng)安備