2017-07-13 546 views
1

我有一個spring-boot服務器應用程序。在功能之一,我跑了一些調度的線程:啓動應用程序彈簧啓動後在類中執行某些方法

private ScheduledExecutorService pool = Executors.newScheduledThreadPool(10); 
    private threadsNumber = 10; 

    @PostConstruct 
    void startThreads() { 
      for (int i = 1; i <= threadsNumber; ++i){ 
       pool.scheduleAtFixedRate(new Runnable() { 
        @Override 
        public void run() { 
          //set Thread Local in depends on i 
          // do some other stuff 

         } 
        } 
       }, 0, 10, TimeUnit.SECONDS); 
      } 
     } 
    } 
} 

的問題是:
如何在春季啓動避免註釋@PostConstruct,並得到一個結果:「啓動應用程序後,執行恰好一次」

+0

在構造函數中執行代碼。 spring會啓動bean,你可以執行你的調度器 – pandaadb

回答

0

Spring提供了ApplicationListener<ContextRefreshedEvent>接口和它的onApplicationEvent(ContextRefreshedEvent event)鉤子。

例如:

public abstract class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> { 

    @Override 
    public void onApplicationEvent(ContextRefreshedEvent event) { 
     // do something on container startup 
    } 
} 
相關問題