实现在Spring Boot中使用MongoDB切换数据源
时间: 2024-03-09 10:48:21 浏览: 146
Spring Boot中使用MongoDB数据库的方法
5星 · 资源好评率100%
在Spring Boot中使用MongoDB切换数据源,可以通过创建多个MongoDB的连接配置和使用`@Qualifier`注解来实现。下面是具体的步骤:
1. 配置多个MongoDB连接信息
在`application.properties`文件中,配置多个MongoDB连接信息,例如:
```
# MongoDB1
spring.data.mongodb1.uri=mongodb://localhost:27017/db1
spring.data.mongodb1.database=db1
spring.data.mongodb1.authentication-database=admin
spring.data.mongodb1.username=user1
spring.data.mongodb1.password=password1
# MongoDB2
spring.data.mongodb2.uri=mongodb://localhost:27017/db2
spring.data.mongodb2.database=db2
spring.data.mongodb2.authentication-database=admin
spring.data.mongodb2.username=user2
spring.data.mongodb2.password=password2
```
2. 创建多个MongoDB的连接配置
创建多个MongoDB的连接配置类,例如:
```
@Configuration
@EnableMongoRepositories(basePackages = "com.example.db1.repositories",
mongoTemplateRef = "mongoDb1Template")
public class MongoDb1Config {
@Bean(name = "mongoDb1Template")
public MongoTemplate mongoTemplate(@Qualifier("mongoDb1Factory") MongoDbFactory mongoDbFactory) {
return new MongoTemplate(mongoDbFactory);
}
@Bean(name = "mongoDb1Factory")
public MongoDbFactory mongoDbFactory() {
MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017/db1");
MongoClient mongoClient = new MongoClient(uri);
return new SimpleMongoDbFactory(mongoClient, "db1");
}
}
@Configuration
@EnableMongoRepositories(basePackages = "com.example.db2.repositories",
mongoTemplateRef = "mongoDb2Template")
public class MongoDb2Config {
@Bean(name = "mongoDb2Template")
public MongoTemplate mongoTemplate(@Qualifier("mongoDb2Factory") MongoDbFactory mongoDbFactory) {
return new MongoTemplate(mongoDbFactory);
}
@Bean(name = "mongoDb2Factory")
public MongoDbFactory mongoDbFactory() {
MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017/db2");
MongoClient mongoClient = new MongoClient(uri);
return new SimpleMongoDbFactory(mongoClient, "db2");
}
}
```
3. 在DAO层使用`@Qualifier`注解
在DAO层使用`@Qualifier`注解指定使用哪个MongoDB连接,例如:
```
@Repository
public class UserRepository {
@Autowired
@Qualifier("mongoDb1Template")
private MongoTemplate mongoDb1Template;
@Autowired
@Qualifier("mongoDb2Template")
private MongoTemplate mongoDb2Template;
public void saveUser1(User user) {
mongoDb1Template.save(user);
}
public void saveUser2(User user) {
mongoDb2Template.save(user);
}
}
```
这样就可以在DAO层通过`@Qualifier`注解来切换不同的MongoDB连接了。
阅读全文