使用Spring Data Mongo配置多个MongoDB存储库 [英] Configure Multiple MongoDB repositories with Spring Data Mongo
问题描述
我有2个Mongodb数据库通过2个MongoTemplate-s连接到Spring Boot应用程序:
I have 2 Mongodb databases connected to a Spring Boot app with 2 MongoTemplate-s:
mongoTemplate (默认bean名称,连接到默认数据库)
mongoTemplate (the default bean name, connects to default db)
mongoAppTemplate (在运行时连接到另一个数据库)
mongoAppTemplate (connects to another database on run-time)
我有很多使用mongoTemplate的MongoRepository-,但我也想创建一些使用mongoAppTemplate的东西.
I have a lot of MongoRepository-s that use mongoTemplate but I also want to create some that would use mongoAppTemplate.
如何配置2个MongoRepository-s以在Java配置中使用不同的MongoTemplate -s?
How can I configure 2 MongoRepository-s to use different MongoTemplate -s with Java configuration ?
我找到了一种使用XML的方法(下面的链接),但我真的想保留所有基于注释的方法
I found a way to do it with XML (link below), but I really want to keep it all annotation based
Spring-data -mongodb在一个Mongo实例中连接到多个数据库
推荐答案
基本思想是将包含您的存储库的包层次结构分为两个不同的路径:
The base idea is to separate the package hierarchy that contains your repositories into two different paths:
-
主要数据库存储库接口的
- com.whatever.repositories.main 包 其他数据库存储库接口的
- com.whatever.repositories.secondary 包
- com.whatever.repositories.main package for the main db repository interfaces
- com.whatever.repositories.secondary package for the other db repository interfaces
您的XML配置应如下所示:
Your XML configuration should be something such as:
<mongo:repositories base-package="com.whatever.repositories.main" mongo-template-ref="mongoTemplate"/>
<mongo:repositories base-package="com.whatever.repositories.secondary" mongo-template-ref="mongoAppTemplate"/>
编辑
@ EnableMongoRepositories 注释不是@Repeatable
,但是您可以有两个@Configuration
类,每个类都用@EnableMongoRepositories
注释,以便使用注释实现相同的目的:
@EnableMongoRepositories annotation is not @Repeatable
, but you can have two @Configuration
classes, each annotated with @EnableMongoRepositories
in order to achieve the same using annotations:
@Configuration
@EnableMongoRepositories(basePackages = "com.whatever.repositories.main", mongoTemplateRef = "mongoTemplate")
public class MainMongoConfig {
....
}
@Configuration
@EnableMongoRepositories(basePackages = "com.whatever.repositories.secondary", mongoTemplateRef = "mongoAppTemplate")
public class SecondaryMongoConfig {
....
}
第三个@Configuration
带注释的类,另外两个@Import
.
And a third @Configuration
annotated class which @Import
the other two.
这篇关于使用Spring Data Mongo配置多个MongoDB存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!