0

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

application.yml:

ansi:
   true

And I have the following @Configuration class:

@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? is it a good practice? Are there any good ways to handle this?

ratzip
  • 1,571
  • 7
  • 28
  • 53
  • You may want to check this: https://stackoverflow.com/questions/22944144/programmatically-shut-down-spring-boot-application#22944850 – Tu.Ma. Nov 08 '18 at 10:06

2 Answers2

0

If a bean throws an exception then Spring will not proceed and the process will end.

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 e.g. X < 10

Michael
  • 41,989
  • 11
  • 82
  • 128
0

We have a lot of options to shutdown spring-boot application:

Shutdown rest endpoint - add below properites to your application.properties and fire following request 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:

  • By calling method close() on ConfigurableApplicationContext object (it will close application context)
  • By passing exit code to method SpringApplication.exit(ctx, () -> 0);

Please check this article for more details.

Kamil W
  • 2,230
  • 2
  • 21
  • 43