简体   繁体   English

抛出BeanCreationException后如何关闭应用程序

[英]How to shut down application after BeanCreationException is thrown

During the startup process, my application creates bean which schedules some tasks in task executor, and then it fails after creating another bean. 在启动过程中,我的应用程序创建了bean,该bean在任务执行程序中安排了一些任务,然后在创建另一个bean之后失败。 This leaves my application in undead state where application looks like it's running but does not provide functionality. 这使我的应用程序处于不死状态,在该状态下,应用程序看起来像在运行,但不提供功能。 I wonder how I could handle BeanCreationException globally to provide proper shutdown. 我不知道如何才能全局处理BeanCreationException以提供适当的关闭。

This is my example code 这是我的示例代码

@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    ExecutorService executorService = Executors.newCachedThreadPool();

    public Application(){
        executorService.submit(()-> {while(true);});
    }

    public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
     }
}

@Service
public class FaultyService {
    public FaultyService(){
        throw new RuntimeException("error");
    }
}

You can add a @PreDestroy to shut down the executor. 您可以添加@PreDestroy以关闭执行程序。 However, it is still the responsibility of your threads to respond to Thread.interrupt() so your infinite while-loop would not be killed, but yours is just a contrived example so I've changed that too: 但是,响应Thread.interrupt()仍然是您线程的责任,因此您的无限while循环不会被杀死,但是您的那只是一个人为的示例,因此我也进行了更改:

@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    ExecutorService executorService = Executors.newCachedThreadPool();

    public Application() {
        executorService.submit(() -> {
            while (true)
            {
                if (Thread.interrupted()) break;
            }
        });
    }

    public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
    }

    @PreDestroy
    public void tearDownExecutor() {
        executorService.shutdownNow();
    }
}

@Service
public class FaultyService {
    public FaultyService(){
        throw new RuntimeException("error");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM