LOOK:SpringBoot 配置 MongoDB 多数据源
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository.first", mongoTemplateRef = "firstMongoTemplate")
public class FirstMongoConfig {
@Bean(name = "firstMongoTemplate")
@Primary
public MongoTemplate firstMongoTemplate() throws Exception {
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://user:pass@localhost:27017/firstDB"));
return new MongoTemplate(mongoClient, "firstDB");
}
}
@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository.second", mongoTemplateRef = "secondMongoTemplate")
public class SecondMongoConfig {
@Bean(name = "secondMongoTemplate")
public MongoTemplate secondMongoTemplate() throws Exception {
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://user:pass@localhost:27017/secondDB"));
return new MongoTemplate(mongoClient, "secondDB");
}
}
这个代码示例展示了如何在Spring Boot应用程序中配置多个MongoDB数据源。每个数据源都有自己的配置类,定义了MongoTemplate bean,并且指定了对应的包路径和数据库名。通过@EnableMongoRepositories
注解,Spring Data MongoDB会为每个数据源创建对应的仓库实例。注意,为了避免潜在的冲突,主要的数据源需要用@Primary
注解标记。
评论已关闭