Java 在Spring引导的运行时指定MongoDb集合名称
我试图在两个不同的微服务中重用我现有的EmployeeRepository代码(见下文),以将数据存储在两个不同的集合中(在同一数据库中)Java 在Spring引导的运行时指定MongoDb集合名称,java,spring,mongodb,spring-boot,Java,Spring,Mongodb,Spring Boot,我试图在两个不同的微服务中重用我现有的EmployeeRepository代码(见下文),以将数据存储在两个不同的集合中(在同一数据库中) @文档(collection=“employee”) 公共接口EmployeeRepository扩展了MongoRepository 是否可以修改@Document(collection=“employee”)以接受运行时参数?例如,类似于@Document(collection=${collection\u NAME})的内容 您是推荐这种方法还是我应
@文档(collection=“employee”)
公共接口EmployeeRepository扩展了MongoRepository
是否可以修改@Document(collection=“employee”)
以接受运行时参数?例如,类似于@Document(collection=${collection\u NAME})
的内容
您是推荐这种方法还是我应该创建一个新的存储库?这不可能,文档中规定集合字段应该是集合名称,因此不是表达式: 至于你的另一个问题-即使传递一个表达式是可能的,我建议创建一个新的存储库类-代码重复不会很糟糕,而且您的微服务可能需要执行不同的查询,而单一存储库类方法将迫使您将所有微服务的查询方法保留在同一个界面中,这不是很干净
看看这段视频,他们列出了一些非常有趣的方法:这是一个非常古老的主题,但我会在这里添加一些更好的信息,以防其他人发现这个讨论,因为事情比公认的答案更灵活 可以使用表达式作为集合名称,因为spel是解析集合名称的可接受方法。例如,如果application.properties文件中有如下属性:
mongo.collection.name = my_docs
@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
}
如果您在配置类中为该属性创建一个Springbean,如下所示:
mongo.collection.name = my_docs
@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
}
然后,您可以将其用作持久性文档模型的集合名称,如下所示:
mongo.collection.name = my_docs
@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
}