Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

Configure Multiple MongoDB repositories with Spring Data Mongo

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

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

mongoAppTemplate (connects to another database on run-time)

I have a lot of MongoRepository-s that use mongoTemplate but I also want to create some that would use mongoAppTemplate.

How can I configure 2 MongoRepository-s to use different MongoTemplate -s with Java configuration ?

I found a way to do it with XML (link below), but I really want to keep it all annotation based

Spring-data-mongodb connect to multiple databases in one Mongo instance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...