java - spring-boot怎样优雅得插入一个后台线程?
巴扎黑
巴扎黑 2017-04-18 10:48:11
0
4
641

我有一个守护,可它需要插入数据到数据库.不知道怎样注入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又开机运行在一个独立线程里呢?

巴扎黑
巴扎黑

모든 응답 (4)
Peter_Zhu

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

根据回答的方法.改为
@Component
class ThreadRun implements DisposableBean.....然后在构造里启动线程,destroy里关闭线程,而且能用到自动注入

    左手右手慢动作

    你的意思是想进行接口的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 name Something like this:       
      PHPzhong

      使用自动注入,把scope配置成prototype试试吧。

        伊谢尔伦

        这个线程是做什么用的?

          최신 다운로드
          더>
          웹 효과
          웹사이트 소스 코드
          웹사이트 자료
          프론트엔드 템플릿
          회사 소개 부인 성명 Sitemap
          PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!