Persistence top

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
Authors Top

If you have a few years of experience in the Java ecosystem, and you’d like to share that with the community, have a look at our Contribution Guidelines.

1. Introduction

In this tutorial, we're going to see different ways to configure a connection to our database. We'll use Spring Boot and Spring Data MongoDB. Exploring Spring's flexible configuration, we'll create a different application for each approach. As a result, we'll be able to choose the most appropriate one.

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, 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 consider the test to be successful. 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. After that, we 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 assert the properties in our inserted document are what we expect.

3. Minimal Setup via 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. We'll see how this works in the following section.

In our application class, we don't need anything special to get up and running:

@SpringBootApplication
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 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 successfully connected using our application.properties file.

3.1. 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 errors.

Options configured this way always have 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. Also, we can 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.2. 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:[email protected]: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 cannot be specified along 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. For instance, using mongodb+srv to connect to a replica set. Therefore, we'll use only 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 sections.

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, let's inject the properties we'll 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 cannot be mixed. Consequently, we cannot reuse our application.properties for this application, and we should move it elsewhere.

AbstractMongoClientConfiguration requires us to override getDatabaseName(). That's because a database name is not 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. Also, we 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. Helpful when we need to set just a few properties programmatically.

5. Conclusion

In this article, we saw 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. Meanwhile, we saw how configuration precedence could affect our connection properties.

And as always, the source code is available over on GitHub.

Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
guest
0 Comments
Inline Feedbacks
View all comments