Specify MongoDb collection name at runtime in Spring boot

雨燕双飞 提交于 2021-02-07 20:13:47

问题


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> 

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?


回答1:


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.

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




回答2:


This is a really old thread, but I will add some better information here in case someone else finds this discussion, because things are a bit more flexible than what the accepted answer claims.

You can use an expression for the collection name because spel is an acceptable way to resolve the collection name. For example, if you have a property in your application.properties file like this:

mongo.collection.name = my_docs

And if you create a spring bean for this property in your configuration class like this:

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

Then you can use that as the collection name for a persistence document model like this:

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


来源:https://stackoverflow.com/questions/31019139/specify-mongodb-collection-name-at-runtime-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!