Mastering MongoDB Connections in Spring Framework
Babak Rosenthal Mohammadi
? General Manager | Automotive Retail & Fixed Ops Strategist | Profitability & Process Optimization | NADA Academy
Introduction:
With the surge in microservices architecture and the need for scalable database solutions, MongoDB has risen as a popular NoSQL database. Coupled with Spring Framework, it provides robust support for creating applications that can interact seamlessly with MongoDB. In this article, we'll walk through the foundational steps to configure and manage MongoDB connections in Spring.
1. The Foundation: AbstractMongoConfig
Every robust system stands on a strong foundation. In the realm of MongoDB configurations with Spring, this foundation is the AbstractMongoConfig class.
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import lombok.Data;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import java.util.Collections;
@Data
public abstract class AbstractMongoConfig {
protected String host, database;
protected String username, password;
protected int port;
/*
* Method that creates MongoDbFactory
* Common to both of the MongoDb connections
*/
public MongoDbFactory mongoDbFactory() {
return new SimpleMongoDbFactory(getMongoClient(), database);
}
/*
* Method that creates MongoClient
*/
private MongoClient getMongoClient() {
return new MongoClient(Collections.singletonList(new ServerAddress(host, port)),
Collections.singletonList(MongoCredential
.createCredential(username, database, password.toCharArray())));
}
/*
* Factory method to create the MongoTemplate
*/
abstract public MongoTemplate getMongoTemplate();
}
Key Takeaways:
领英推荐
2. Applying the Foundation: Setting Up a Specific Connection
Building on our foundation, let's see how to set up a specific MongoDB connection using the ExampleDevMongoConnection class.
package com.example.calculationcommon.config.mongo;
import com.example.calculationcommon.config.AbstractMongoConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@Configuration
@EnableMongoRepositories(basePackages = {"com.example.calculationcommon.repository"}, mongoTemplateRef = "exampleDevMongoTemplate")
@ConfigurationProperties(prefix = "example.db")
public class ExampleDevMongoConnection extends AbstractMongoConfig {
@Value("${example.db.host}")
String dbHost;
@Value("${example.db.port}")
int dbPort;
@Value("${example.db.database}")
String db;
@Value("${example.db.username}")
String dbUsername;
@Value("${example.db.password}")
String dbPassword;
@Override
@Bean(name = "exampleDevMongoTemplate")
public MongoTemplate getMongoTemplate() {
this.host = dbHost;
this.port = dbPort;
this.database = db;
this.username = dbUsername;
this.password = dbPassword;
return new MongoTemplate(mongoDbFactory());
}
}
Highlights:
Conclusion:
Connecting Spring Framework with MongoDB doesn't have to be daunting. With a strong foundational class and understanding of how Spring annotations work, we can efficiently set up and manage MongoDB connections. Whether you're building a small application or an enterprise solution, these configurations will ensure your database interactions are seamless.
If you found this guide helpful, please give it a thumbs up and share it with your network. For any queries or discussions, drop a comment below!