问题描述
如何以编程方式关闭Spring Boot应用程序而不终止虚拟机?
在其他作品中,与
new SpringApplication(Main.class).run(args);
推荐答案
关闭一个 SpringApplication
基本上意味着关闭底层的ApplicationContext
.SpringApplication#run(String...)
方法为您提供 ApplicationContext
作为 ConfigurableApplicationContext代码>.然后你可以
close()
自己动手.
Closing a SpringApplication
basically means closing the underlying ApplicationContext
. The SpringApplication#run(String...)
method gives you that ApplicationContext
as a ConfigurableApplicationContext
. You can then close()
it yourself.
例如
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to shut down...
ctx.close();
}
}
或者,您可以使用 static
SpringApplication.exit(ApplicationContext, ExitCodeGenerator...)
a> helper 方法来为你做这件事.例如,
Alternatively, you can use the static
SpringApplication.exit(ApplicationContext, ExitCodeGenerator...)
helper method to do it for you. For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to stop...
int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
@Override
public int getExitCode() {
// no errors
return 0;
}
});
// or shortened to
// int exitCode = SpringApplication.exit(ctx, () -> 0);
System.exit(exitCode);
}
}
这篇关于以编程方式关闭 Spring Boot 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!