Java 初始化时关闭弹簧

Java 初始化时关闭弹簧,java,spring,intellij-idea,spring-boot,Java,Spring,Intellij Idea,Spring Boot,所以我在Tomcat上运行了一个Spring应用程序。在部署初始化时,我有时可能会遇到一些错误(例如,找不到某些JDNI值或应用程序无法连接到某些服务)。因此,当发生这种情况时,我抛出异常并在@Configuration文件中捕获它。在catch块中,我尝试使用System.exit(-1)关闭应用程序。但这似乎不是正确的方法。因为Intellij没有能力或关闭服务器,我甚至看到在服务器关闭之前不会释放资源 我也尝试过: @Autowired public ApplicationContext

所以我在Tomcat上运行了一个Spring应用程序。在部署初始化时,我有时可能会遇到一些错误(例如,找不到某些JDNI值或应用程序无法连接到某些服务)。因此,当发生这种情况时,我抛出异常并在@Configuration文件中捕获它。在catch块中,我尝试使用System.exit(-1)关闭应用程序。但这似乎不是正确的方法。因为Intellij没有能力或关闭服务器,我甚至看到在服务器关闭之前不会释放资源

我也尝试过:

@Autowired
public ApplicationContext application context
@Bean
public IServerDataCache serverDataCache() {
    try {
        return new ServerDataCache(args);
    } catch(InitializationError initializationError) {
        log.error("Unable to load configuration for Server Data Cache. Closing application.");
        System.exit(1); OR SpringApplication.exit(applicationContext)
    }
    return null;
}
两个系统。出口(1);或者SpringApplication.exit(applicationContext)似乎也有同样的效果。有没有更好的方法来强制应用程序终结的想法


顺便说一句,这是一个spring启动应用程序。

只需让您的
@Bean
方法抛出异常即可。虽然Andy Wilkinson的回答是正确的,但我想补充一点,因为您是在Tomcat上运行应用程序(而不是嵌入式的Tomcat),当应用程序无法启动时,Tomcat服务器不会关闭。 这是出于设计,因为Tomcat和所有JavaEE容器一样,意味着要同时运行多个应用程序


如果您希望在应用程序失败时停止整个过程,则需要切换到使用嵌入式容器。

为了澄清,建议如下:@Bean public IServerDataCache serverDataCache()抛出初始化错误{返回新的serverDataCache(args);}是的,这就是我的意思