问题描述
我正在阅读此Git问题: https://github.com/spring-projects/spring-boot/issues/7589 关于Java Spring引导的问题,并正在尝试找出一种在启动时绕过崩溃的方法.
I was reading through this Git issue:https://github.com/spring-projects/spring-boot/issues/7589with regards to Java Spring boot and am trying to figure out a way to bypass the crash upon startup.
简短的版本是,如果您包含用于创建mongo客户端的代码:
The short version is that If you include the code for creating the mongo client:
@Bean
public MongoOperations mongoOperations() {
try {
//This runs an operation which uses my credentials to login to the db
return new MongoTemplate(mongoDbFactory());
} catch (Exception e){
e.printStackTrace();
return null;
}
}
并且MongoDB正在运行,它将连接并且没有任何问题,但是,如果MongoDB没有运行 ,Spring将重试,并且在再次失败后将崩溃并停止所有启动序列.
and the MongoDB is running, it will connect and not have any problems, but if the MongoDB is not running, Spring will retry and after failing again, will crash and stop all startup sequences.
我的问题是:除了注释掉引用它的所有代码之外,是否有办法绕过此初始崩溃/检查数据库是否已启动并正在运行?我可以在某个低级别的地方捕获异常并让其通过吗?
推荐答案
如果您的应用程序表现为MongoDB是可选的,则您有几种选择.
If your application behaves in such a way that MongoDB is optional, you have several options.
如果要迁移现有应用程序,那么从一开始最简单的方法是到排除自动配置并自行创建基础架构.从您指示从@Bean
方法返回null
的方式并不是很讨厌.相反,您可以拥有一些可以延迟创建客户端的服务,并且可以更新MongoDB的可选用法以通过该服务.无论如何都将创建该服务,但仅在必要时创建基础基础结构.
If you are migrating an existing application, the easiest from a start would be to exclude the auto-configuration and create the infrastructure yourself. Not in the way you've indicated as returning null
from a @Bean
method is quite nasty. Rather you could have some service that could lazily create the client and you could update your optional usages of MongoDB to go through that service. The service would be created regardless but would only create the underlying infrastructure if necessary.
另一个选择是使用配置文件.如果主要用例是MongoDB可用,则创建application-nomongo.properties
(类似),在其中您可以使用spring.autoconfigure.exclude
属性排除自动配置.当应用程序在没有mongo的情况下启动时,您可以启用nomongo
配置文件,并且自动配置将退出.如果未启用,则Mongo
bean将由Spring Boot创建.
The other option is to use a profile. If the main use case is that MongoDB is available then create a application-nomongo.properties
(something like that) where you would exclude the auto-configuration using the spring.autoconfigure.exclude
property. When the application starts without mongo, you can enable the nomongo
profile and the auto-configuration will backoff. When it's not enabled, the Mongo
bean will be created by Spring Boot.
这篇关于如何在禁用MongoDB但仍安装了MongoDB的情况下运行Spring?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!