在 Spring Boot 运行时指定 MongoDb 集合名称 [英] Specify MongoDb collection name at runtime in Spring boot

查看:196
本文介绍了在 Spring Boot 运行时指定 MongoDb 集合名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在两个不同的微服务中重用我现有的 EmployeeRepository 代码(见下文),以将数据存储在两个不同的集合中(在同一个数据库中).

I am trying to reuse my existing EmployeeRepository code (see below) in two different microservices to store data in two different collections (in the same database).

@Document(collection = "employee")
public interface EmployeeRepository extends MongoRepository<Employee, String> 

是否可以修改 @Document(collection = "employee") 以接受运行时参数?例如类似于 @Document(collection = ${COLLECTION_NAME}).

Is it possible to modify @Document(collection = "employee") to accept runtime parameters? For e.g. something like @Document(collection = ${COLLECTION_NAME}).

您会推荐这种方法还是我应该创建一个新的存储库?

Would you recommend this approach or should I create a new Repository?

推荐答案

应该不可能,文档指出集合字段应该是集合名称,因此不是表达式:http://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/mapping/Document.html

It shouldn't be possible, the documentation states that the collection field should be collection name, therefore not an expression: http://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/mapping/Document.html

就您的其他问题而言 - 即使可以传递表达式,我也会建议创建一个新的存储库类 - 代码重复也不错,而且您的微服务可能需要执行不同的查询和单个存储库类这种方法会迫使您将所有微服务的查询方法保留在同一个接口中,这不是很干净.

As far as your other question is concerned - even if passing an expression was possible, I would recommend creating a new repository class - code duplication would not be bad and also your microservices may need to perform different queries and the single repository class approach would force you to keep query methods for all microservices within the same interface, which isn't very clean.

看看这个视频,他们列出了一些非常有趣的方法:http://www.infoq.com/presentations/Micro-Services

Take a look at this video, they list some very interesting approaches: http://www.infoq.com/presentations/Micro-Services

这篇关于在 Spring Boot 运行时指定 MongoDb 集合名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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