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

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

巴扎黑
巴扎黑

reply all(4)
Peter_Zhu

Sorry everyone, I found a way myself.: http://stackoverflow.com/ques...

According to the answer, change it to
@Component
class ThreadRun implements DisposableBean.... Then start the thread in the structure, close the thread in destroy, and you can use automatic injection

左手右手慢动作

You mean you want to automatically inject the beans of the interface, right? You can refer to spring's injection of abstract class beans or interface objects
Create an abstract class DataService implements Runnable for injection. Then extend it.
Because the life cycle of springbean is completed when the beanFactory is created, your object needs to be injected only when it is created, which conflicts with the concept of spring.

The following is taken from 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:

<bean id="abstractBaseClass" abstract="true" class="pacakge1.AbstractBaseClass">
  <property name="mailserver" value="DefaultMailServer"/>
</bean>

<bean id="concreteClass1" class="pacakge1.ConcreteClass1" parent="abstractBaseClass">     
  <!--Override the value of the abstract based class if necessary-->
  <property name="mailserver" value="AnotherMailServer"/>
</bean>
PHPzhong

Use automatic injection and try configuring scope as prototype.

伊谢尔伦

What is this thread used for?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template