使用 Spring Data Mongo 配置多个 MongoDB 存储库 [英] Configure Multiple MongoDB repositories with Spring Data Mongo

查看:53
本文介绍了使用 Spring Data Mongo 配置多个 MongoDB 存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 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-s,但我也想创建一些使用 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 以使用不同的 MongoTemplate -s 和 Java 配置?

我找到了一种使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆