配置嵌入式MongoDB的最简单方法 [英] The easiest way to configure Embedded MongoDB

查看:62
本文介绍了配置嵌入式MongoDB的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,有没有示例如何使用Spring Boot正确配置嵌入式MongoDB?

I'm wondering, is there any example how to properly configure embedded MongoDB with Spring Boot?

例如,这是我配置H2嵌入式数据库的方式:

For example, this is how i configure H2 embedded database:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.jndi.JndiObjectFactoryBean;

import javax.sql.DataSource;


@Configuration
@PropertySource({"configs/datasource.properties"})
public class DataSourceConfig {

    @Bean
    @Profile("test")
    public DataSource testDataSource() {
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
    }
}

这很好用,但是有一个问题.这种方法不提供MongoDB的配置.

And this works well, but there is a problem. This approach doesnt provide configuration with MongoDB.

有没有解决方法?

更新1:

[错误]无法执行目标 org.springframework.boot:spring-boot-maven-plugin:1.5.6.RELEASE:run (default-cli)在项目XXX上:发生异常 跑步. null:InvocationTargetException:使用以下命令创建bean时出错 类路径资源中定义的名称"mongoTemplate" [com/reborn/XXX/config/DataSourceConfig .class]:Bean 通过工厂方法实例化失败;嵌套的异常是 org.springframework.beans.BeanInstantiationException:失败 实例化[org.springframewor k.data.mongodb.core.MongoTemplate]: 工厂方法"mongoTemplate"抛出异常;嵌套的异常是 java.lang.NoClassDefFoundError:de/flapdoodle/embed/mongo/distribu tion/IFeatureAwareVersion: de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion-> [帮助 1]

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.6.RELEASE:run (default-cli) on project XXX: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/reborn/XXX/config/DataSourceConfig .class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframewor k.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoClassDefFoundError: de/flapdoodle/embed/mongo/distribu tion/IFeatureAwareVersion: de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion -> [Help 1]

更新2:

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>com.reborn</groupId>
    <artifactId>xxx</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>xxx</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repositories -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>cz.jirutka.spring</groupId>
            <artifactId>embedmongo-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

DatasourceConfig:

package com.reborn.xxx.config;

import com.mongodb.MongoClient;
import cz.jirutka.spring.embedmongo.EmbeddedMongoFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.io.IOException;

@Configuration
public class DataSourceConfig {

    @Bean
    public MongoTemplate mongoTemplate() throws IOException {
        EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();
        mongo.setBindIp("localhost");
        MongoClient mongoClient = mongo.getObject();
        MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "abcd");
        return mongoTemplate;
    }

}

更新3:

[错误]无法在项目星巴克-finder上执行目标org.springframework.boot:spring-boot-maven-plugin:1.5.6.RELEASE:run(default-cli):发生异常 跑步. null:InvocationTargetException:创建类路径资源[com/reborn/xxx/config/DataSourceConfig中定义的名称为'mongoTemplate'的bean时出错 .class]:通过工厂方法实例化Bean失败;嵌套的异常是org.springframework.beans.BeanInstantiationException:无法实例化[org.springframewor k.data.mongodb.core.MongoTemplate]:工厂方法"mongoTemplate"抛出异常;嵌套的异常是java.lang.IllegalArgumentException:此版本不支持 32位:PRODUCTION:Windows:B32-> [帮助1]

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.6.RELEASE:run (default-cli) on project starbucks-finder: An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/reborn/xxx/config/DataSourceConfig .class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframewor k.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.IllegalArgumentException: this version does not support 32Bit: PRODUCTION:Windows:B32 -> [Help 1]

推荐答案

flapdoodle嵌入式MongoDB 可以与Spring Boot集成.

The flapdoodle embedded MongoDB can be integrated with Spring Boot.

  • 声明对flappedoodle的依赖:

  • Declare a dependency on flapdoodle:

<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <version>2.0.0</version>
</dependency>

  • 声明对该库的依赖关系,以便为flappoodle的嵌入式MongoDB提供Spring工厂bean:

  • Declare a dependency on the library, to provide a Spring factory bean for flapdoodle's embedded MongoDB:

    <dependency>
        <groupId>cz.jirutka.spring</groupId>
        <artifactId>embedmongo-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
    

  • 大概是您已经声明了对spring-boot-starter-data-mongodb的依赖关系:

  • Presumably, you have already declared a dependency on spring-boot-starter-data-mongodb:

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

  • 现在,只需配置指向嵌入式MongoDB实例的MongoTemplate:

    @Bean
    public MongoTemplate mongoTemplate() throws IOException {
        EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();
        mongo.setBindIp("localhost");
        MongoClient mongoClient = mongo.getObject();
        MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "test_or_whatever_you_want_to_call_this_db");
        return mongoTemplate;
    }
    

  • 这篇关于配置嵌入式MongoDB的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆