【问题标题】:How to configure Spring Repository to use mongoTemplate defined in xml bean?如何配置 Spring Repository 以使用 xml bean 中定义的 mongoTemplate?
【发布时间】:2015-02-19 18:05:29
【问题描述】:

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

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

【问题讨论】:

  • 您还有其他配置吗?这似乎是书本上的。
  • 没有。我试图弄清楚如何将外部定义的属性传递给spring应用程序,这是我在阅读了很多文章后的第一次尝试。我想知道是否应该从 MongoRepository 扩展 PlaylistRepository 而不仅仅是存储库。会试一试的。
  • Spring boot 自动配置可能会获取您的 spring-data-mongodb 依赖项并自动配置您的 mongo 存储库。 Spring 是如何知道您的mongo-context.xml 的?我没有看到它在任何地方被引用

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


【解决方案1】:

我假设您使用 Spring Boot 是因为它的自动配置功能和自以为是的默认设置。如果是这样,您应该让 Spring 配置您的 Mongo 存储库。

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

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

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

<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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 2012-10-28
      相关资源
      最近更新 更多