Srini K
Srini K

Reputation: 3365

How to configure Spring Repository to use mongoTemplate defined in xml bean?

The code executes fine, but creates collections in default mongo database and location i.e in test database @ localhost:27017. In the mongoTemplate bean wired through the below xml, I'm using mydb as database with mongod instance running at localhost:27018. However, the data still gets persisted to default instance and database.

MongoDB XML Bean defined in src/main/resources/mongo-context.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:mongo="http://www.springframework.org/schema/data/mongo"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/data/mongo
    http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">

  <mongo:mongo id="mongo" host="localhost" port="27018"/>

  <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongo" />
    <constructor-arg value="mydb" />
  </bean>

  <mongo:repositories base-package="core.repository" mongo-template-ref="mongoTemplate"/>
</beans>

Playlist repository:

package core.repository;

import core.dao.Playlist;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.repository.Repository;

/**
 * This repository provides CRUD operations for {@link core.dao.Playlist} objects.
 */
public interface PlaylistRepository extends Repository<Playlist, String> {

    /**
     * Finds the information of a single Playlist entry.
     * @param id    The id of the requested Playlist entry.
     * @return      The information of the found Playlist entry. If no Playlist entry
     *              is found, this method returns an empty {@link java.util.Optional} object.
     */
    Optional<Playlist> findOne(String id);

    /**
     * Saves a new Playlist entry to the database.
     * @param saved The information of the saved Playlist entry.
     * @return      The information of the saved Playlist entry.
     */
    Playlist save(Playlist saved);
}

Playlist service that uses repository:

package core.service;

import core.dao.*;
import core.error.NotFoundException;
import core.repository.PlaylistRepository;
import core.simulator.PlaylistServiceSimulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Executes the business logic promised by the {@link core.service.PlaylistService} interface.
 */
@Service
final class PlaylistServiceExecutor implements PlaylistService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PlaylistServiceExecutor.class);

    private final PlaylistRepository repository;
    private final PlaylistServiceSimulator simulator;

    @Autowired
    PlaylistServiceExecutor(PlaylistRepository repository, PlaylistServiceSimulator simulator) {
        this.repository = repository;
        this.simulator = simulator;
    }

    @Override
    public PlaylistDTO create(PlaylistDTO playlist) {
        LOGGER.debug("Creating a new Playlist entry with information: {}", playlist);

        Playlist persisted = Playlist.build()
        persisted = repository.save(persisted);
        LOGGER.debug("Created a new Playlist entry with information: {}", persisted);

        return persisted.toDTO();
    }

    @Override
    public PlaylistDTO findById(String id) {
        LOGGER.debug("Finding Playlist entry with id: {}", id);

        Playlist found = findPlaylistById(id);

        LOGGER.debug("Found Playlist entry: {}", found);

        return found.toDTO();
    }

    private Playlist findPlaylistById(String id) {
        Optional<Playlist> result = repository.findOne(id);
        return result.orElseThrow(() -> new NotFoundException(id));
    }
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>myapp</groupId>
    <artifactId>core</artifactId>
    <version>0.1</version>

    <properties>
        <!-- Enable Java 8 -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- Configure the main class of our Spring Boot application -->
        <start-class>core.CoreApp</start-class>
    </properties>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.9.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Get the dependencies of a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <!-- Spring Data MongoDB-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>1.7.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>0.9.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path-assert</artifactId>
            <version>0.9.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Spring Boot Maven Support -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Finally, SpringApplication boot class CoreApp:

package core;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * This configuration class has three responsibilities:
 * <ol>
 *     <li>It enables the auto configuration of the Spring application context.</li>
 *     <li>
 *         It ensures that Spring looks for other components (controllers, services, and repositories) from the
 *         <code>core</code> package.
 *     </li>
 *     <li>It launches our application in the main() method.</li>
 * </ol>
 */
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class CoreApp {

    public static void main(String[] args) {
        SpringApplication.run(CoreApp.class, args);
    }
}

Upvotes: 4

Views: 24721

Answers (2)

akinKaplanoglu
akinKaplanoglu

Reputation: 768

You can use applicationContext.xml file for this. It looks like below:

<?xml version="1.0" encoding="UTF-8"?>

<beans default-lazy-init="true" xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
            http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/data/mongo
            http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
    <description><![CDATA[
        Main entry point for spring configuration
    ]]></description>



        <!-- Connection to MongoDB server -->

    <mongo:db-factory host="localhost" port="27017" dbname="test" />
    <!-- MongoDB Template -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
      <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>

    <!-- Package w/ automagic repositories -->
    <mongo:repositories base-package="com.bedas.ays.mongo" />



</beans>

Upvotes: 3

ikumen
ikumen

Reputation: 11643

I'm assuming you're using Spring boot for it's auto configuration features and opinionated defaults. If so, you should let Spring configure your Mongo repository.

Remove your mongo configuration in src/main/resources/mongo-context.xml Replace the mongo dependency

<dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
</dependency>

with the following Spring boot dependency to pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
</dependencies>

Make sure your repositories extend MongoRepository

Have at least the following properties in your application.properties. See Spring Boot appendix for properties reference

spring.data.mongodb.uri=mongodb://localhost:27018/mydb
spring.data.mongo.repositories.enabled=true

Here are some additional guides:

  1. https://spring.io/guides/gs/accessing-data-mongodb/
  2. http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-nosql.html

Upvotes: 5

Related Questions