Configure Multiple MongoDB repositories with Spring Data Mongo

前端 未结 1 1285
轻奢々
轻奢々 2020-12-02 00:33

I have 2 Mongodb databases connected to a Spring Boot app with 2 MongoTemplate-s:

mongoTemplate (the default bean name, connects to default db)

相关标签:
1条回答
  • 2020-12-02 00:41

    The base idea is to separate the package hierarchy that contains your repositories into two different paths:

    • com.whatever.repositories.main package for the main db repository interfaces
    • com.whatever.repositories.secondary package for the other db repository interfaces

    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"/>
    

    EDIT

    @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 {
        ....
    }
    

    And a third @Configuration annotated class which @Import the other two.

    0 讨论(0)
提交回复
热议问题