gpt4 book ai didi

java - 启动应用程序 spring-boot 后执行类中的某些方法

转载 作者:行者123 更新时间:2023-11-30 06:36:48 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com