Home  >  Q&A  >  body text

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又开机运行在一个独立线程里呢?

巴扎黑巴扎黑2721 days ago684

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:50:11

    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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:50:11

    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>

    reply
    0
  • PHPz

    PHPz2017-04-18 10:50:11

    Use automatic injection and try configuring scope as prototype.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:50:11

    What is this thread used for?

    reply
    0
  • Cancelreply