这个问题在这里已有答案:
在我的应用程序中,我需要使用两个MongoDB数据库。我不知道如何在spring应用程序的application.properties文件中添加2个MongoDB数据库。
这是我的项目的application.properties文件,
spring.data.mongodb.database=DB1
spring.data.mongodb.authentication-database=DB1
spring.data.mongodb.host=dev-ng-mongo1.domain.com
spring.data.mongodb.password=9876512
spring.data.mongodb.port=27017
spring.data.mongodb.username=pavan
但我想在同一个项目中使用另一个MongoDB数据库。如何在application.properties文件中添加新数据库。
请按照以下步骤设置多个mongodb数据源。
######Primary Mongo DB########################
spring.data.mongodb.host=localhost
spring.data.mongodb.database=primary
spring.data.mongodb.port=27017
spring.data.mongodb.password=*******
spring.data.mongodb.username=*******
###########Secondary MongoDB#####################
mongodb.host=localhost
mongodb.port=27017
mongodb.database=secondary
mongodb.username=******
mongodb.password=******
@Configuration
public class MultipleMongoConfig {
@Primary
@Bean(name = "primary")
@ConfigurationProperties(prefix = "spring.data.mongodb")
public MongoProperties getPrimary() {
return new MongoProperties();
}
@Bean(name = "secondary")
@ConfigurationProperties(prefix = "mongodb")
public MongoProperties getSecondary() {
return new MongoProperties();
}
@Primary
@Bean(name = "primaryMongoTemplate")
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory(getPrimary()));
}
@Bean(name = "secondaryMongoTemplate")
public MongoTemplate secondaryMongoTemplate() throws Exception {
return new MongoTemplate(secondaryFactory(getSecondary()));
}
@Bean
@Primary
public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
@Bean
public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
mongo.getDatabase());
}
。请确保你在这里更改EnableMongoRepositories
你的存储库包
basePackages = "com.example.springbootmultipledatasource.primary.repository"
辅助Mongo模板:请确保您在此处更改辅助存储库包@Configuration
@EnableMongoRepositories(basePackages =
"com.example.springbootmultipledatasource.primary.repository",
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {
}
basePackages = "com.example.springbootmultipledatasource.secondary.repository
现在你可以创建你的文档,存储库,服务,控制器,你很高兴。我可以创建或者有不同的项目结构。
@Configuration
@EnableMongoRepositories(basePackages = "com.example.springbootmultipledatasource.secondary.repository",
mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig {
}