Springboot 2.x 多个 mongodb 数据源 MongoTemplate home 编辑时间 2019/08/23 ![](/api/file/getImage?fileId=5d5e604416199b2a52001a90) ## 简介 多数据源有很多好处,根据重要性区别备份,也可以区别分配资源等 网上查了很多例子都是针对`Repository`用法的mongodb多数据源 奈何我就喜欢用MongoTemplate 参考了以下这篇博客,自己实现了一下mongodb 多数据源 搭配多个MongoTemplate 参考:[https://blog.csdn.net/u011663149/article/details/88634598](https://blog.csdn.net/u011663149/article/details/88634598) ## 代码 ### 配置源 **application.yml** ```yml test1: mongodb: host:localhost port:27001 database:test1 test2: mongodb: host:localhost port:27001 database:test2 ``` ### springboot配置类 **AbstractMongoConfig.java** ```java package com.zzzmh.api.config; import com.mongodb.MongoClient; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; public abstract class AbstractMongoConfig { private String host; private String database; private int port; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public MongoDbFactory mongoDbFactory() throws Exception { return new SimpleMongoDbFactory(new MongoClient(host, port), database); } abstract public MongoTemplate getMongoTemplate() throws Exception; } ``` **Test1MongoConfig.java** ```java @Configuration @ConfigurationProperties(prefix = "test1.mongodb") public class Test1MongoConfig extends AbstractMongoConfig { /** * @Primary 设为默认 * MongoTemplate实现 */ @Primary @Override public @Bean(name = "test1MongoTemplate") MongoTemplate getMongoTemplate() throws Exception { return new MongoTemplate(mongoDbFactory()); } } ``` **Test2MongoConfig.java** ```java @Configuration @ConfigurationProperties(prefix = "test2.mongodb") public class Test2MongoConfig extends AbstractMongoConfig { /** * MongoTemplate实现 */ @Override public @Bean(name = "test2MongoTemplate") MongoTemplate getMongoTemplate() throws Exception { return new MongoTemplate(mongoDbFactory()); } } ``` ### 用法 使用Qualifier配置MongoTemplate用哪个数据源 不配置则使用默认数据源 ```java @Autowired @Qualifier(value = "test1MongoTemplate") private MongoTemplate mongoTemplate; ``` ## END 送人玫瑰,手留余香 赞赏 Wechat Pay Alipay Linux Deepin 15.11 安装PxCook 第二弹!基于PlayOnLinux Springboot 2.x 整合 quartz 定时任务 实现动态添加、暂停、删除等功能