gpt4 book ai didi

java - 了解 Spring Boot 的应用程序生命周期和启动监听器

转载 作者:行者123 更新时间:2023-11-30 01:45:38 26 4
gpt4 key购买 nike

在 Sprint Boot 2.x 中,我们可以通过以下两种方法之一初始化我们的应用程序:

@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
init();
}

private void init() {
// Init the app from in here...
}
}

或者我们可以使用将在启动时执行的启动监听器:

public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// Init the app from in here...
}
}

我想知道采用任何一种方法都存在哪些权衡。对 Spring Boot 的“应用程序生命周期”了解不多,我想知道在这两种设置中是否有我将/不会访问的东西。提前致谢!

最佳答案

init 方法仅在启动后调用,并且仅在将应用程序作为命令行程序运行时调用。

init 方法例如将应用程序部署为 .war 文件时不会调用。

每当 ContextRefreshedEvent 时,就会调用 onApplicationEvent 方法。被激发,这确实在启动期间发生,但可以稍后再次调用。参见例如“When is ContextRefreshedEvent fired in Spring?

要获得与 init 方法更具可比性的事件,请使用 ApplicationStartedEvent .

关于java - 了解 Spring Boot 的应用程序生命周期和启动监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102386/

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