markdown MongoDB数据源配置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown MongoDB数据源配置相关的知识,希望对你有一定的参考价值。
**Maven**
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
```
## 数据源配置
```java
@Configuration
//禁用spring boot的自动配置
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
//激活@Repository注解,并且设置dao扫描包
@EnableMongoRepositories(basePackages = "cn.datawin.dao.mongodb.manager", mongoTemplateRef = "masterMongoHelper")
public class MasterMongoDbConfig {
@Bean(name = "masterMongoProperties")
@ConfigurationProperties(prefix = "spring.data.mongodb.master")
@Primary
public MongoProperties mongoProperties() {
return new MongoProperties();
}
@Bean(name = "masterMongoClientFactory")
@Primary
public MongoClientFactory mongoClientFactory(@Qualifier("masterMongoProperties") MongoProperties properties, Environment environment) {
return new MongoClientFactory(properties, environment);
}
@Bean(name = "masterMongoClient")
@Primary
public MongoClient mongoClient(@Qualifier("masterMongoClientFactory") MongoClientFactory factory) {
return factory.createMongoClient(null);
}
@Bean(name = "masterMongoDbFactory")
@Primary
public MonthlyMongoDbFactory mongoDbFactory(@Qualifier("masterMongoClient") MongoClient mongoClient, @Qualifier("masterMongoProperties") MongoProperties properties) {
//这里new我们自己的MongoDbFactory即可
return new MonthlyMongoDbFactory(mongoClient, properties.getDatabase());
}
@Bean(name = "masterMongoHelper")
@Primary
public MongoHelper mongoTemplate(@Qualifier("masterMongoDbFactory") MonthlyMongoDbFactory mongoDbFactory) {
return new MongoHelper(mongoDbFactory);
}
}
/**
* 继承 {@link SimpleMongoDbFactory },重写{@code getDB}方法,添加月库
*
* @author fonlin
* @date 2018/6/28
*/
public class MonthlyMongoDbFactory extends SimpleMongoDbFactory {
/**
* 没有分月库的数据库
*/
private String databaseName;
public MonthlyMongoDbFactory(MongoClientURI uri) {
super(uri);
}
public MonthlyMongoDbFactory(MongoClient mongoClient, String databaseName) {
super(mongoClient, databaseName);
this.databaseName = databaseName;
}
public MongoDatabase getDb(String dbName) throws DataAccessException {
return super.getDb(dbName);
}
}
```
以上是关于markdown MongoDB数据源配置的主要内容,如果未能解决你的问题,请参考以下文章
markdown [MongoDB] Awesome Cheatsheet #mongodb #cheatsheet
markdown MongoDB中的中间件
markdown MongoDB查询
markdown MongoDB备忘单
markdown MongoDB的
markdown Spring:MongoDB