2017-07-13 274 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 
    } 
} 
相关问题