一、配置文件
pom.xml
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.yml
spring:application:name: double-mongoprofiles:active: devjackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8server:port: 8008sys:mongodb:one:uri: mongodb://user01:admin123@192.168.1.2:10135,192.168.1.3:10135/mongo01two:uri: mongodb://user02:admin123@192.168.1.2:10135,192.168.1.3:10135/mongo02
二、配置Configuration Bean
(1)第一个mongodb配置(主)
public class OneMongoConfig {private MongoClient mongo;@Primary//必须设置默认的mongo模板,默认名字必须为mongoTemplate@Bean("mongoTemplate")public MongoTemplate oneMongoTemplate(@Autowired @Qualifier("oneMongoDbFactory")MongoDbFactory mongoDbFactory, MongoConverter converter) {return new MongoTemplate(mongoDbFactory, converter);}@Primary//必须设置默认的mongo工厂@Beanpublic MongoDbFactory oneMongoDbFactory(@Autowired @Qualifier("oneMongoProperties")MongoProperties properties,Environment environment, ObjectProvider<MongoClientOptions> options) {MongoClientOptions _options = options.getIfAvailable();MongoClientFactory mongoClientFactory = new MongoClientFactory(properties, environment);this.mongo = mongoClientFactory.createMongoClient(_options);return new SimpleMongoDbFactory(this.mongo, properties.getMongoClientDatabase());}@PreDestroypublic void close() {if (this.mongo != null) {this.mongo.close();}}@Primary//必须设置默认的mongo配置@Bean@ConfigurationProperties(prefix = "sys.mongodb.one")public MongoProperties oneMongoProperties(){return new MongoProperties();}}
(2)第二个mongo配置
public class TwoMongoConfig {private MongoClient mongo;@Beanpublic MongoTemplate twoMongoTemplate(@Autowired @Qualifier("twoMongoDbFactory")MongoDbFactory mongoDbFactory, MongoConverter converter) {return new MongoTemplate(mongoDbFactory, converter);}@Beanpublic MongoDbFactory twoMongoDbFactory(@Autowired @Qualifier("twoMongoProperties")MongoProperties properties,Environment environment, ObjectProvider<MongoClientOptions> options) {MongoClientOptions _options = options.getIfAvailable();MongoClientFactory mongoClientFactory = new MongoClientFactory(properties, environment);this.mongo = mongoClientFactory.createMongoClient(_options);return new SimpleMongoDbFactory(this.mongo, properties.getMongoClientDatabase());}@PreDestroypublic void close() {if (this.mongo != null) {this.mongo.close();}}@Bean@ConfigurationProperties(prefix = "sys.mongodb.two")public MongoProperties twoMongoProperties(){return new MongoProperties();}}
(3)mongo导入配置
@Configuration
@Import({OneMongoConfig.class, TwoMongoConfig.class})
public class MongoConfig {}
注意:去掉默认自动配置
@SpringBootApplication(exclude = {MongoAutoConfiguration.class})
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
SpringBoot2.1.9 多MongoDB配置自动扫描_茅坤宝骏氹的博客-CSDN博客