[英]how to close the application during startup in spring boot
I have a question regarding the startup in spring boot
, how to close the application during the startup time, for example, I have the following 我有一个关于
spring boot
,如何在启动期间关闭应用程序,例如,我有以下内容
application.yml
: application.yml
:
ansi:
true
And I have the following @Configuration
class: 我有以下
@Configuration
类:
@Configuration
class AppConfig {
@Value('${ansi}')
String ansi;
@Bean
getAnsi() {
if(ansi.equals("true")) {
Ansi ansiObj = new Ansi();
ansiObj.ansi = ansi;
return ansiObj;
}
}
}
class Ansi {
String ansi;
}
When ansi
in the application.yml
is true
, it continue, otherwise, the application should be closed, can we close the application during the bean creation? 当
application.yml
ansi
为true
,它将继续,否则,应关闭该应用程序,我们可以在bean创建期间关闭该应用程序吗? is it a good practice? 这是一个好习惯吗? Are there any good ways to handle this?
有什么好的方法可以解决这个问题?
If a bean throws an exception then Spring will not proceed and the process will end. 如果bean抛出异常,那么Spring将不会继续进行,并且该过程将结束。
if(ansi.equals("true")) {
Ansi ansiObj = new Ansi();
ansiObj.ansi = ansi;
return ansiObj;
}
else {
throw new IllegalArgumentException("reason");
}
I can't say that I've ever had a use-case for it, but I wouldn't say it's necessary bad practice. 我不能说我曾经有过用例,但我不会说这是必要的坏习惯。 In this limited example of true and false, it seems a bit unusual.
在这个对与错的有限示例中,这似乎有点不寻常。 It would make more sense if you needed a constraint on a property eg X < 10
如果您需要对属性进行约束,例如X <10
We have a lot of options to shutdown spring-boot application: 我们有很多选项可以关闭spring-boot应用程序:
Shutdown rest endpoint - add below properites to your application.properties and fire following request curl -X POST localhost:port/actuator/shutdown
关闭其余端点-在您的application.properties中添加以下属性,并在请求
curl -X POST localhost:port/actuator/shutdown
management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true
endpoints.shutdown.enabled=true
Also you can call suitable method to shutdown application: 您也可以调用合适的方法来关闭应用程序:
close()
on ConfigurableApplicationContext
object (it will close application context) ConfigurableApplicationContext
对象调用close()
方法(它将关闭应用程序上下文) SpringApplication.exit(ctx, () -> 0);
SpringApplication.exit(ctx, () -> 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.