- 注入依赖
<!-- spring-boot-starter-data-mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- yml文件添加配置
#mongo配置
spring:
data:
mongodb:
primary:
host: localhost
port: 27017
database: sc-db
secondary:
host: localhost
port: 27017
database: sc-test
- 设置数据源的mongoTemplate模板
3.1):设置primary数据源的mongoTemplate模板
package org.sc.service.os.utils.mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
im