1. Overview
In this tutorial, weโll learn different ways to configure a MongoDB connection in a Spring Boot application. Weโll use the powerful capabilities offered by the Spring Data MongoDB project. By leveraging the Spring Data MongoDB project, we gain access to a rich set of tools and functionalities that streamline the process of working with MongoDB databases in a Spring environment.
By delving into Springโs flexible configuration options, weโll explore various approaches for establishing database connections. Through hands-on examples, weโll create separate applications for each approach, enabling us to select the most appropriate configuration method tailored to our specific requirements.
2. Testing Our Connections
Before we start building our applications, weโll create a test class. Letโs start with a few constants weโll reuse:
public class MongoConnectionApplicationLiveTest {
private static final String HOST = "localhost";
private static final String PORT = "27017";
private static final String DB = "baeldung";
private static final String USER = "admin";
private static final String PASS = "password";
// test cases
}
Our tests consist of running our application, and then trying to insert a document in a collection called โitemsโ. After inserting our document, we should receive an โ_idโ from our database, and weโll consider the test successful. Now letโs create a helper method for that:
private void assertInsertSucceeds(ConfigurableApplicationContext context) {
String name = "A";
MongoTemplate mongo = context.getBean(MongoTemplate.class);
Document doc = Document.parse("{\"name\":\"" + name + "\"}");
Document inserted = mongo.insert(doc, "items");
assertNotNull(inserted.get("_id"));
assertEquals(inserted.get("name"), name);
}
Our method receives the Spring context from our application so that we can retrieve the MongoTemplate instance. Next, weโll build a simple JSON document from a string with Document.parse().
This way, we donโt need to create a repository or a document class. Then, after inserting, weโll assert the properties in our inserted document are what we expect.
Itโs important to note that we need to run a real MongoDB instance. For this, we can run MongoDB as a docker container.
3. Configuring Connections via Properties
To configure MongoDB connections in our Spring Boot application, we typically use properties. In properties, we define essential connection details such as the database host, port, authentication credentials, and database name. Weโll see these properties in detail in the following subsections.
3.1. Using the application.properties
Our first example is the most common way of configuring connections. We just have to provide our database information in our application.properties:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=baeldung
spring.data.mongodb.username=admin
spring.data.mongodb.password=password
All available properties reside in the MongoProperties class from Spring Boot. We can also use this class to check default values. We can define any configuration in our properties file via application arguments.
In our application class, we need to exclude the EmbeddedMongoAutoConfiguration class to get up and running:
@SpringBootApplication(exclude={EmbeddedMongoAutoConfiguration.class})
public class SpringMongoConnectionViaPropertiesApp {
public static void main(String... args) {
SpringApplication.run(SpringMongoConnectionViaPropertiesApp.class, args);
}
}
This configuration is all we need to connect to our database instance. The @SpringBootApplication annotation includes @EnableAutoConfiguration. It takes care of discovering that our application is a MongoDB application based on our classpath.
To test it, we can use SpringApplicationBuilder to get a reference to the application context. Then, to assert our connection is valid, weโll use the assertInsertSucceeds method created earlier:
@Test
public void whenPropertiesConfig_thenInsertSucceeds() {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class);
app.run();
assertInsertSucceeds(app.context());
}
In the end, our application was successfully connected using our application.properties file.
3.2. Overriding Properties With Command Line Arguments
We can override our properties file when running our application with command line arguments. These are passed to the application when run with the java command, mvn command, or IDE configuration. The method to provide these will depend on the command weโre using.
Letโs see an example using mvn to run our Spring Boot application:
mvn spring-boot:run -Dspring-boot.run.arguments='--spring.data.mongodb.port=7017 --spring.data.mongodb.host=localhost'
To use it, we specify our properties as values to the spring-boot.run.arguments argument. We use the same property names but prefix them with two dashes. Since Spring Boot 2, multiple properties should be separated by a space. Finally, after running the command, there shouldnโt be any errors.
Options configured this way always take precedence over the properties file. This option is useful when we need to change our application parameters without changing our properties file. For instance, if our credentials have changed and we canโt connect anymore.
To simulate this in our tests, we can set system properties before running our application. We can also override our application.properties with the properties method:
@Test
public void givenPrecedence_whenSystemConfig_thenInsertSucceeds() {
System.setProperty("spring.data.mongodb.host", HOST);
System.setProperty("spring.data.mongodb.port", PORT);
System.setProperty("spring.data.mongodb.database", DB);
System.setProperty("spring.data.mongodb.username", USER);
System.setProperty("spring.data.mongodb.password", PASS);
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
.properties(
"spring.data.mongodb.host=oldValue",
"spring.data.mongodb.port=oldValue",
"spring.data.mongodb.database=oldValue",
"spring.data.mongodb.username=oldValue",
"spring.data.mongodb.password=oldValue"
);
app.run();
assertInsertSucceeds(app.context());
}
As a result, the old values in our properties file wonโt affect our application because system properties have more precedence. This can be useful when we need to restart our application with new connection details without changing the code.
3.3. Using the Connection URI Property
Itโs also possible to use a single property instead of the individual host, port, etc.:
spring.data.mongodb.uri="mongodb://admin:password@localhost:27017/baeldung"
This property includes all values from the initial properties, so we donโt need to specify all five. Letโs check the basic format:
mongodb://<username>:<password>@<host>:<port>/<database>
The database part in the URI is, more specifically, the default auth DB. Most importantly, the spring.data.mongodb.uri property canโt be specified along with the individual ones for host, port, and credentials. Otherwise, weโll get the following error when running our application:
@Test
public void givenConnectionUri_whenAlsoIncludingIndividualParameters_thenInvalidConfig() {
System.setProperty(
"spring.data.mongodb.uri",
"mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB
);
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaPropertiesApp.class)
.properties(
"spring.data.mongodb.host=" + HOST,
"spring.data.mongodb.port=" + PORT,
"spring.data.mongodb.username=" + USER,
"spring.data.mongodb.password=" + PASS
);
BeanCreationException e = assertThrows(BeanCreationException.class, () -> {
app.run();
});
Throwable rootCause = e.getRootCause();
assertTrue(rootCause instanceof IllegalStateException);
assertThat(rootCause.getMessage()
.contains("Invalid mongo configuration, either uri or host/port/credentials/replicaSet must be specified"));
}
In the end, this configuration option is not only shorter but sometimes required. Thatโs because some options are only available through the connection string, like using mongodb+srv to connect to a replica set. As such, weโll only use this simpler configuration property for the next examples.
4. Java Setup With MongoClient
MongoClient represents our connection to a MongoDB database and is always created under the hood, but we can also set it up programmatically. Despite being more verbose, this approach has a few advantages. Letโs take a look at them over the next few subsections.
4.1. Connecting via AbstractMongoClientConfiguration
In our first example, weโll extend the AbstractMongoClientConfiguration class from Spring Data MongoDB in our application class:
@SpringBootApplication
public class SpringMongoConnectionViaClientApp extends AbstractMongoClientConfiguration {
// main method
}
Next, weโll inject the properties we need:
@Value("${spring.data.mongodb.uri}")
private String uri;
@Value("${spring.data.mongodb.database}")
private String db;
To clarify, these properties could be hard-coded. Also, they could use names that differ from the expected Spring Data variables. Most importantly, this time weโre using a URI instead of individual connection properties, which canโt be mixed. Consequently, we canโt reuse our application.properties for this application, and we should move it elsewhere.
AbstractMongoClientConfiguration requires us to override getDatabaseName(). This is because a database name isnโt required in a URI:
protected String getDatabaseName() {
return db;
}
At this point, because weโre using default Spring Data variables, weโd already be able to connect to our database. Also, MongoDB creates the database if it doesnโt exist. Letโs test it:
@Test
public void whenClientConfig_thenInsertSucceeds() {
SpringApplicationBuilder app = new SpringApplicationBuilder(SpringMongoConnectionViaClientApp.class);
app.web(WebApplicationType.NONE)
.run(
"--spring.data.mongodb.uri=mongodb://" + USER + ":" + PASS + "@" + HOST + ":" + PORT + "/" + DB,
"--spring.data.mongodb.database=" + DB
);
assertInsertSucceeds(app.context());
}
Finally, we can override mongoClient() to get an advantage over conventional configuration. This method will use our URI variable to build a MongoDB client. That way, we can have a direct reference to it. For instance, this enables us to list all the databases available from our connection:
@Override
public MongoClient mongoClient() {
MongoClient client = MongoClients.create(uri);
ListDatabasesIterable<Document> databases = client.listDatabases();
databases.forEach(System.out::println);
return client;
}
Configuring connections this way is useful if we want complete control over the MongoDB clientโs creation.
4.2. Creating a Custom MongoClientFactoryBean
In our next example, weโll create a MongoClientFactoryBean. This time, weโll create a property called custom.uri to hold our connection configuration:
@SpringBootApplication
public class SpringMongoConnectionViaFactoryApp {
// main method
@Bean
public MongoClientFactoryBean mongo(@Value("${custom.uri}") String uri) {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
ConnectionString conn = new ConnectionString(uri);
mongo.setConnectionString(conn);
MongoClient client = mongo.getObject();
client.listDatabaseNames()
.forEach(System.out::println);
return mongo;
}
}
With this approach, we donโt need to extend AbstractMongoClientConfiguration. We also have control over our MongoClientโs creation. For instance, by calling mongo.setSingleton(false), we get a new client every time we call mongo.getObject(), instead of a singleton.
4.3. Set Connection Details With MongoClientSettingsBuilderCustomizer
In our last example, weโre going to use a MongoClientSettingsBuilderCustomizer:
@SpringBootApplication
public class SpringMongoConnectionViaBuilderApp {
// main method
@Bean
public MongoClientSettingsBuilderCustomizer customizer(@Value("${custom.uri}") String uri) {
ConnectionString connection = new ConnectionString(uri);
return settings -> settings.applyConnectionString(connection);
}
}
We use this class to customize parts of our connection but still have auto-configuration for the rest. This is helpful when we need to set just a few properties programmatically.
5. Conclusion
In this article, we examined the different tools brought by Spring Data MongoDB. We used them to create connections in different ways. Moreover, we built test cases to guarantee our configurations worked as intended. Finally, we saw how configuration precedence could affect our connection properties.
