我正在尝试使用 SpringBoot 与 Mongo 数据库通信。
它正在使用 spring-boot-starter-data-mongodb 并自动配置默认 bean,这确实允许我的 MongoRepository 类与数据库正常通信。
但是,我想覆盖默认值。我可以使用 application.properties,但我需要能够在应用程序启动时将连接参数作为命令行上的选项传递。
我尝试更改端口来破坏它,我已将调试添加到 Mongo 配置中,似乎无论我做什么,默认的 spring 配置都会被使用。就好像 @Configuration 注解被忽略了。
我尝试了各种配置主应用程序类的方式(指定conf位置,将@Configuration添加到主类,有或没有@SpringBootApplication ...),但这是我现在所处的位置......
package somepackage
@EnableAutoConfiguration
@ComponentScan
public class MyApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
....
}
package somepackage.conf; // should be picked up by ComponentScan, no?
@Configuration
public class MongoConf {
@Bean
public MongoClientFactoryBean mongo() throws Exception {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
/*
setting to silly values to try to prove it is trying to create connections using this bean - expected to see errors because can't create connection... */
mongo.setHost("flibble");
mongo.setPort(345);
return mongo;
}
}
最佳答案
您实际上应该通过应用程序属性使用内置的 Spring Boot MongoDb Starter 功能和相关的自动配置。自定义主机、端口、密码等可以而且应该通过专用 Spring Boot MongoDB Properties 设置:
spring.data.mongodb.authentication-database= # Authentication database name.
spring.data.mongodb.database=test # Database name.
spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.host=localhost # Mongo server host.
spring.data.mongodb.password= # Login password of the mongo server.
spring.data.mongodb.port=27017 # Mongo server port.
spring.data.mongodb.repositories.enabled=true # Enable Mongo repositories.
spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. When set, host and port are ignored.
spring.data.mongodb.username= # Login user of the mongo server.
支持属性的完整列表的链接是 here .
关于java - 为什么我的 Spring Boot (mongo) bean 没有被创建/使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40772980/