在 Spring 启动时在运行时指定 MongoDb 集合名称

Specify MongoDb collection name at runtime in Spring boot

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

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

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

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

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

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

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

这是一个非常古老的话题,但我会在此处添加一些更好的信息以防其他人发现此讨论,因为事情比接受的答案声称的要灵活一些。

您可以对集合名称使用表达式,因为 spel 是解析集合名称的可接受方式。例如,如果您的 application.properties 文件中有这样一个 属性:

mongo.collection.name = my_docs

并且如果您在配置 class 中为此 属性 创建一个 spring bean,如下所示:

@Bean("myDocumentCollection")
public String mongoCollectionName(@Value("${mongo.collection.name}") final String collectionName) {
    return collectionName
}

然后您可以将其用作持久性文档模型的集合名称,如下所示:

@Document(collection = "#{@myDocumentCollection}")
public class SomeModel {
    @Id
    private String id;
    // other members and accessors/mutators
    // omitted for brevity
}