Using Spring Data with MongoDB: Configuring JavaConfig

Configure the Spring environment with plain old Java objects (POJOs) using JavaConfig. A POJO is an ordinary Java object without any special constraints of Java object models or conventions. The base class for Spring Data MongoDB configuration with JavaConfig is org.springframework.data.mongodb.config. AbstractMongoConfiguration.

  1. Create a class, SpringMongoApplicationConfig, which declares some @Bean methods and extends the org.springframework.data.mongodb.config. AbstractMongoConfiguration class.
  2. Annotate the class with @Configuration, which indicates that the class is processed by the Spring container to generate bean definitions and service requests for the beans at runtime.
  3. Declare a @Bean annotated method that returns a MongoClient instance. The SpringMongoApplicationConfig class must implement the inherited abstract methods getDatabaseName() and mongo(). The localhost host name (the IP address may also be used) and port number 27017 are used to create a MongoClient instance.
  1. Also override the non-abstract method getMappingBasePackage to return the package (com.mongo.model) in which the model class is defined.

The Spring configuration class SpringMongoApplicationConfig is listed below.

package com.mongo.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

import org.springframework.context.annotation.Bean;

import com.mongo.service.CatalogService;

import com.mongodb.Mongo;

import com.mongodb.MongoClient;

import com.mongodb.ServerAddress;

import java.util.Arrays;

@Configuration

public class SpringMongoApplicationConfig extends AbstractMongoConfiguration {

@Override

@Bean

public Mongo mongo() throws Exception {

return new MongoClient(Arrays.asList(new ServerAddress(“localhost”, 27017)));

}

@Override

protected String getDatabaseName() {

return “local”;

}

@Override

protected String getMappingBasePackage() {

return “com.mongo.model”;

}

}

Source: Vohra Deepak (2015), Pro MongoDB™ Development, Apress; 1st ed. edition.

Leave a Reply

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