Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I abort Spring-Boot startup?

I'm writing a Spring-Boot application to monitor a directory and process files that are being added to it. I register the directory with WatchService in a configuration class:

@Configuration
public class WatchServiceConfig {

    private static final Logger logger = LogManager.getLogger(WatchServiceConfig.class);

    @Value("${dirPath}")
    private String dirPath;

    @Bean
    public WatchService register() {
        WatchService watchService = null;

        try {
            watchService = FileSystems.getDefault().newWatchService();
            Paths.get(dirPath).register(watchService, ENTRY_CREATE);
            logger.info("Started watching \"{}\" directory ", dlsDirPath);
        } catch (IOException e) {
            logger.error("Failed to create WatchService for directory \"" + dirPath + "\"", e);
        }

        return watchService;
    }
}

I would like to abort Spring Boot startup gracefully if registering the directory fails. Does anybody know how I can do this?

like image 645
Zhubin Salehi Avatar asked Dec 02 '16 20:12

Zhubin Salehi


People also ask

How do I stop spring boot from running?

Another option to shutdown the Spring Boot application is to close Spring ApplicationContext using SpringApplication . SpringApplication. run(String…) method returns ApplicationContext as a ConfigurableApplicationContext We can use close() method to close ApplicationContext programmatically.

How do you stop spring boot Microservices?

If you have Spring Boot Actuator included in your project, you can enable a shutdown endpoint (by default it is not enabled). This means that if you make a request to: http://yourserver.com/yourapp/shutdown, the application will shutdown gracefully.


1 Answers

The accepted answer is correct, but unnecessarily complex. There's no need for a Condition, and then checking for the existence of the bean, and then closing the ApplicationContext. Simply checking for the presence of the directory during WatchService creation, and throwing an exception will abort the application startup due to failure to create the bean.

like image 53
Abhijit Sarkar Avatar answered Oct 23 '22 12:10

Abhijit Sarkar