我有一个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
并得到结果:“启动应用程序后仅执行一次” 最佳答案
Spring提供了ApplicationListener<ContextRefreshedEvent>
接口及其onApplicationEvent(ContextRefreshedEvent event)
挂钩。
例如:
public abstract class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// do something on container startup
}
}