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. javascript - 一排三个框,各个框的间距是15px,距离外面的白框间距也是15px,这个css怎么写?2. javascript - Vue 的依赖追踪属于单向数据绑定还是双向绑定?3. html5 - javascript写业务有用到什么编程范式没?4. javascript - vue 数据更新了。但是dom没有更新,,,,,如图5. javascript - jQuery post()方法,里面的请求串可以转换为GBK编码么?可以的话怎样转换?6. javascript - vue 手机端项目在进入主页后 在进入子页面,直接按返回出现空白情况7. 网页爬虫 - python爬虫翻页问题,请问各位大神我这段代码怎样翻页,还有价格要登陆后才能看到,应该怎么解决8. html5 - vue-cli 装好了 新建项目的好了,找不到项目是怎么回事?9. mysql - C#连接数据库时一直这一句出问题int i = cmd.ExecuteNonQuery();10. javascript - 哪位大神指导下,如何实现今日头条头部导航列表,点那个类型,哪种类型就居中了?

网公网安备