我有一个 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>
接口(interface)及其onApplicationEvent(ContextRefreshedEvent event)
钩。
例如:
public abstract class MyServiceCreationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// do something on container startup
}
}
关于java - 启动应用程序 spring-boot 后执行类中的某些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45084679/