ホームページ  >  に質問  >  本文

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日前682

全員に返信(4)返信します

  • 天蓬老师

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

    皆さんごめんなさい、私は自分で方法を見つけました。: http://stackoverflow.com/ques...

    答えによると、それを
    @Component
    class ThreadRunimplements DisposableBean....に変更します。その後、構造内でスレッドを開始し、destroyでスレッドを閉じると、自動インジェクションを使用できます

    返事
    0
  • ringa_lee

    ringa_lee2017-04-18 10:50:11

    インターフェースの Bean を自動的に注入したいということですよね? Spring の抽象クラス Bean またはインターフェイス オブジェクトのインジェクションを参照できます
    インジェクション用の Runnable を実装する抽象クラス DataService を作成します。それから延長します。
    springbean のライフサイクルは beanFactory の作成時に完了するため、オブジェクトは作成時にのみ注入する必要があり、これは Spring の概念と矛盾します。

    以下はスタックオーバーフローからの抜粋です

    リーリー

    返事
    0
  • PHPz

    PHPz2017-04-18 10:50:11

    自動インジェクションを使用して、プロトタイプとしてスコープを構成してみてください。

    返事
    0
  • 伊谢尔伦

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

    このスレッドは何に使われますか?

    返事
    0
  • キャンセル返事