国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

java - spring-boot怎樣優(yōu)雅得插入一個(gè)后臺(tái)線程?

瀏覽:127日期:2024-02-07 09:57:52

問(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ú)立線程里呢?

問(wèn)題解答

回答1:

不好意思各位,我自己找到方法了.:http://stackoverflow.com/ques...

根據(jù)回答的方法.改為@Componentclass ThreadRun implements DisposableBean.....然后在構(gòu)造里啟動(dòng)線程,destroy里關(guān)閉線程,而且能用到自動(dòng)注入

回答2:

你的意思是想進(jìn)行接口的bean自動(dòng)注入吧? 你可以參考spring關(guān)于抽象類的bean或接口對(duì)象的注入創(chuàng)建一個(gè)抽象類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è)線程是做什么用的?

標(biāo)簽: java
相關(guān)文章:
主站蜘蛛池模板: 抚州市| 万盛区| 五寨县| 吴江市| 枞阳县| 鄂托克旗| 抚州市| 湘潭县| 富民县| 新乡市| 上蔡县| 大新县| 松滋市| 紫阳县| 江达县| 乃东县| 福清市| 高淳县| 大关县| 徐闻县| 盖州市| 习水县| 内黄县| 红安县| 铜鼓县| 伊宁市| 吕梁市| 江山市| 资溪县| 江陵县| 乌拉特前旗| 永泰县| 志丹县| 久治县| 永仁县| 寿阳县| 甘德县| 河东区| 田林县| 清原| 平远县|