启动应用程序spring-boot

时间:2017-07-13 15:09:32

标签: java spring spring-boot threadpool

我有一个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);
            }
        }
    }
}

问题是:
如何在spring-boot中避免注释@PostConstruct并获得结果:“在启动app后执行一次”

1 个答案:

答案 0 :(得分:1)

Spring提供ApplicationListener<ContextRefreshedEvent>接口及其onApplicationEvent(ContextRefreshedEvent event)挂钩。

例如:

public abstract class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {

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