依赖
// build.gradle
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
配置文件
spring:
data:
mongodb:
primary:
uri: mongodb://localhost:27017/db1
secondary:
uri: mongodb://localhost:27017/db2
主数据库配置
package com.fengwenyi.springboot_mongo_multi_source.config;
import com.mongodb.MongoClientURI;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@Configuration
@EnableMongoRepositories(basePackages = "com.fengwenyi.springboot_mongo_multi_source.primary",
mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig {
@Bean
@Primary
@ConfigurationProperties(prefix="spring.data.mongodb.primary")
public MongoProperties primaryMongoProperties() {
return new MongoProperties();
}
@Primary
@Bean(name = "primaryMongoTemplate")
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory(primaryMongoProperties()));
}
@Bean
@Primary
public MongoDbFactory primaryFactory(MongoProperties mongoProperties) throws Exception {
return new SimpleMongoDbFactory(new MongoClientURI(primaryMongoProperties().getUri()));
}
}
副数据库配置
package com.fengwenyi.springboot_mongo_multi_source.config;
import com.mongodb.MongoClientURI;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation