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

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

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

MongoDB XML Bean 定义在 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>

播放列表存储库:

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

我假设您正在使用 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 中至少具有以下属性。请参阅 Spring properties reference

的引导附录
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

您可以为此使用 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>