如何配置Spring Repository以使用xml bean中定义的mongoTemplate?

时间:2015-02-19 18:05:30

标签: spring mongodb spring-boot spring-data-mongodb

代码执行正常,但在默认的mongo数据库和位置创建集合,即 test database @ localhost:27017。在通过以下xml连接的mongoTemplate bean中,我使用 mydb 作为数据库,并在localhost:27018上运行mongod实例。但是,数据仍然会持久保存到默认实例和数据库。

在src / main / resources / mongo-context.xml中定义的MongoDB XML Bean:

<?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>

播放列表存储库:

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);
}

使用存储库的播放列表服务:

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>

最后,SpringApplication启动类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);
    }
}

2 个答案:

答案 0 :(得分:5)

我假设你正在使用Spring启动它的自动配置功能和固定默认值。如果是这样,您应该让Spring配置您的Mongo存储库。

删除src/main/resources/mongo-context.xml中的mongo配置 替换mongo依赖

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

具有以下Spring引导依赖关系pom.xml

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

确保您的存储库扩展MongoRepository

application.properties至少包含以下属性。请参阅properties reference

的Spring Boot附录
spring.data.mongodb.uri=mongodb://localhost:27018/mydb
spring.data.mongo.repositories.enabled=true

以下是一些其他指南:

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

答案 1 :(得分:3)

您可以使用applicationContext.xml文件。它看起来如下:

<?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>