JavaSpringTechnology

Spring Boot Multiple MongoTemplates

Hi Readers,
In this post we are going to talk about creating multiple Mongo Templates in a Spring Boot backed application. Spring Boot helps us concentrate on our business logic only and takes care of all the application related configurations. Spring Boot’s powerful auto configuration help us writing our applications very fast.

How Spring Boot Creates a Mongo Connection:

To create MongoTemplate instance through Spring Boot we only need to provide Mongo Server details in Spring Boot specific property keys and Spring Boot on startup automatically creates a Mongo Connection with Mongo Template wrapper and let’s us Auto wire wherever we want to use.
Below are the basic properties required for creating a MongoTemplate.

Spring Boot has a class called as MongoProperties.java which defines the mandatory property key prefix as ‘spring.data.mongodb’ (can be seen in the above properties extract). The MongoProperties.java holds all the mongo properties that we wrote in the application.properties. Then there is another class called as MongoDataAutoConfiguration.java which uses the MongoProperties.java as its Properties Configuration Class and is responsible for actually creating the MongoTemplate through one of its factory methods

To connect to two different mongo server I would have required to override all these classes and their behaviours. To avoid this I used a simple technic as described below.

Configuring Multiple MongoTemplates:

First of all I modified application.properties and added two sets of Mongodb connection details like shown below.

Doing this the Spring Boots default auto-configuration of MongoTemplate would go on toss as it doesn’t find the required keys in the properties file. In this case Spring Boot will create a MongoTemplate with default host and post (localhost:27017). Before we end I will also tell how did I avoid that.

Below are the simple classes I created.

Look at the @Primary annotation here. It will tell Spring to load this MongoTemplate by default when nothing is provided.

That’s what we need to do. Now we are just left with using the MongoTemplates. Below are the examples how can we use it.

I am Technology enthusiast who loves to learn and adapt to newer programming practices and trends, and have huge passion for sharing what I know.
I work as a Technology Lead in Java Platform, and have little more than a decade of experience in Design, Code, Refactor, Test, and Deploy large scale applications as well as micro-services.
Apart from programming, I love Photography, Music creation, Fictions, Ghazals and Cooking. If you share any of the common interests, feel free to buzz. You comments, suggestions, and appreciations are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *