配置嵌入式MongoDB的最简单方法

时间:2017-08-30 09:05:02

标签: java spring mongodb spring-boot

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

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

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的配置。

有没有解决方法?

更新1:

  

[错误]无法执行目标   org.springframework.boot:弹簧启动了Maven插件:1.5.6.RELEASE:运行   项目XXX上的(default-cli):发生异常时   运行。 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   重刑/ IFeatureAwareVersion:   de.flapdoodle.embed.mongo.distribution.IFeatureAwareVersion - > [救命   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:

  

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

3 个答案:

答案 0 :(得分:4)

flapdoodle embedded MongoDB可以与Spring Boot集成。

  • 声明对flapdoodle的依赖:

    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <version>2.0.0</version>
    </dependency>
    
  • 声明对库的依赖,为flapdoodle的嵌入式MongoDB提供Spring工厂bean:

    <dependency>
        <groupId>cz.jirutka.spring</groupId>
        <artifactId>embedmongo-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
    
  • 据推测,您已经声明了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;
    }
    

答案 1 :(得分:1)

对于具有JUnit5的Spring Boot 2.2.x

pom.xml

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <scope>test</scope>
        </dependency>

测试课程
(具有设置MongoDB版本的功能)

@ExtendWith(SpringExtension.class)
@DataMongoTest
class ModelRepoIntegrationTest {

    private static final String IP = "localhost";
    private static final int PORT = 28017; // <- set MongoDB port

    @TestConfiguration
    @Import(ModelRepo.class) // <- set the tested repository
    // @ComponentScan("com.example.repo") <- or package for several repositories
    static class Config {
        @Bean
        public IMongodConfig embeddedMongoConfiguration() throws IOException {
            return new MongodConfigBuilder()
                    .version(Version.V4_0_2) // <- set MongoDB version
                    .net(new Net(IP, PORT, Network.localhostIsIPv6()))
                    .build();
        }
    }

    @Autowired private ModelRepo repo; // <- tested repository
    @Autowired private MongoTemplate mongo; 

    @BeforeEach
    void setUp() { // clean db (slower) or collection (faster) before each test
        // mongo.getDb().drop();
        mongo.remove(new Query(), Model.class); 
    }

    @Test
    void create() {
        Model model = new Model() // <- tested entity
                          .setId(UUID.randomUUID())
                          .setNum(1)
                          .setText("text");
        Model actual = repo.create(model); // <- tested method of the repository
        List<Model> models = mongo.findAll(Model.class);
        assertThat(models).hasSize(1);
        Model expected = models.get(0);
        assertThat(actual).isEqualToComparingFieldByField(expected);
    }
}

答案 2 :(得分:0)

它将使用相关依赖项的新版本或可复合版本进行自动配置

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </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-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>
            <version>1.50.5</version>
        </dependency>
        <dependency>
            <groupId>cz.jirutka.spring</groupId>
            <artifactId>embedmongo-spring</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

    </dependencies>

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


        @Repository
public interface yourRepository extends MongoRepository<Class Type, String> {

}