Spring Data MongoDB Configuration

Use Java configuration to set up Spring Data MongoDB.

Example Details

The example demonstrates how to:

  • Extend AbstractMongoConfiguration and override the necessary methods for our environment.
  • Activate MongoDB repositories and specify their location using @EnableMongoRepositories.
  • Use the @Configuration and @Bean annotations to set up our beans.
  • Create the MongoClient and set the default write concern to SAFE.
  • Register MongoTemplate as a bean.

AbstractMongoConfiguration

AbstractMongoConfiguration provides a default set of infrastructure components and provides callback methods to tweak the configuration as necessary.

mongo() creates a MongoClient object which contains an internal connection pool. This connects to the database returned by getDatabaseName() on the specified host using the default port (27017).

getMappingBasePackage() returns the base package to scan for mapped Documents.

@EnableMongoRepositories activates the MongoDB repository infrastructure, and basePackageClasses specifies the package(s) to scan for the repositories.

So in this case, Spring Data locates the RepositoryPackage interface in 'com.lishman.springdata.repository', and registers all the repository classes in this package.

MongoTemplate is also created as a bean to be used in the integration tests, as we will see later.

MongoConfig.java
package io.lishman.springdata.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import io.lishman.springdata.repository.RepositoryPackage;
import io.lishman.springdata.template.TemplatePackage;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;

@Configuration
@EnableMongoRepositories(basePackageClasses=RepositoryPackage.class)
@ComponentScan(basePackageClasses=TemplatePackage.class)
public class MongoConfig extends AbstractMongoConfiguration {
    
    // ---------------------------------------------------- mongodb config

    @Override
    protected String getDatabaseName() {
        return "world";
    }

    @Override
    @Bean
    public MongoClient mongo() throws Exception {
        MongoClient client = new MongoClient("mongo");
        client.setWriteConcern(WriteConcern.SAFE);
        return client;
    }

    @Override
    protected String getMappingBasePackage() {
        return "io.lishman.springdata.domain";
    }
    
    // ---------------------------------------------------- MongoTemplate
    
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongo(), getDatabaseName());
    }
    
}