springboot整合mongodb(一)

环境:Intellij IDEA 2019.1.3、Java11.0.3、mongodb4.0.10

参考资料:https://spring.io/guides/gs/accessing-data-mongodb/

https://medium.com/@gtommee97/rest-api-java-spring-boot-and-mongodb-4dffbcabbaf5

一、创建简单maven项目springboot-mongodb

二、pom文件引入相关依赖

<?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.zsx</groupId>
    <artifactId>springboot-mongodb</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath />
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
        </dependency>
        <!-- junit5运行所需jar包 -->
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 自动配置包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 引入热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

三、application.yml文件中添加mongodb配置

spring: 
  servlet:
    multipart:
      # 设置文件上传大小
      max-file-size: 20MB
      max-request-size: 20MB
  data: 
    mongodb:
#      uri: mongodb://zsx:1234@localhost:27017/mongodb_test
      database: mongodb_test
      host: localhost
      port: 27017
      username: test
#       不通过urI连接时,密码不要设纯数字,否则可能会出错
      password: a1234

注意:非uri方式连接时,密码不建议设纯数字原因请参考Mongodb4.0使用问题记录

四、创建实体类Customer.java

package com.zsx.entity;

import org.springframework.data.annotation.Id;


public class Customer {

    @Id
    public String id;

    public String firstName;
    public String lastName;

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%s, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

五、创建数据处理接口CustomerRepository.java

package com.zsx.repository;

import com.zsx.entity.Customer;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {
    
}

六、创建启动器引导类MongoDBApplication.java

package com.zsx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MongoDBApplication {

    public static void main(String[] args) {
        SpringApplication.run(MongoDBApplication.class, args);
    }
}

七、创建测试类CustomerRepositoryTest.java

package com.zsx.test.repositoty;

import com.zsx.entity.Customer;
import com.zsx.repository.CustomerRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class CustomerRepositoryTest {

    @Autowired
    private CustomerRepository repository;

    @Test
    void testSave() {
        repository.save(new Customer("zhangsan", "zhangsanfeng"));
    }
}

八、运行测试方法testSave

H:\JDK\jdk-11.0.3\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:H:\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=50364:H:\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath "H:\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar;H:\JetBrains\IntelliJ IDEA 2019.1.3\plugins\junit\lib\junit-rt.jar;H:\JetBrains\IntelliJ IDEA 2019.1.3\plugins\junit\lib\junit5-rt.jar;E:\maven\repository\org\junit\vintage\junit-vintage-engine\5.3.2\junit-vintage-engine-5.3.2.jar;E:\maven\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;E:\maven\repository\org\junit\platform\junit-platform-engine\1.3.2\junit-platform-engine-1.3.2.jar;E:\maven\repository\org\junit\platform\junit-platform-commons\1.3.2\junit-platform-commons-1.3.2.jar;E:\maven\repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;E:\maven\repository\junit\junit\4.12\junit-4.12.jar;E:\maven\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;F:\IdeaProjects\springbootmongodb\target\test-classes;F:\IdeaProjects\springbootmongodb\target\classes;E:\maven\repository\org\springframework\boot\spring-boot-starter-web\2.1.4.RELEASE\spring-boot-starter-web-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter\2.1.4.RELEASE\spring-boot-starter-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-logging\2.1.4.RELEASE\spring-boot-starter-logging-2.1.4.RELEASE.jar;E:\maven\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;E:\maven\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;E:\maven\repository\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;E:\maven\repository\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;E:\maven\repository\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\maven\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;E:\maven\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-json\2.1.4.RELEASE\spring-boot-starter-json-2.1.4.RELEASE.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-tomcat\2.1.4.RELEASE\spring-boot-starter-tomcat-2.1.4.RELEASE.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.17\tomcat-embed-core-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.17\tomcat-embed-el-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.17\tomcat-embed-websocket-9.0.17.jar;E:\maven\repository\org\hibernate\validator\hibernate-validator\6.0.16.Final\hibernate-validator-6.0.16.Final.jar;E:\maven\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;E:\maven\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;E:\maven\repository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;E:\maven\repository\org\springframework\spring-web\5.1.6.RELEASE\spring-web-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-beans\5.1.6.RELEASE\spring-beans-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-webmvc\5.1.6.RELEASE\spring-webmvc-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-aop\5.1.6.RELEASE\spring-aop-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-context\5.1.6.RELEASE\spring-context-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-expression\5.1.6.RELEASE\spring-expression-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-data-mongodb\2.1.4.RELEASE\spring-boot-starter-data-mongodb-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-mongodb\2.1.6.RELEASE\spring-data-mongodb-2.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-tx\5.1.6.RELEASE\spring-tx-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-commons\2.1.6.RELEASE\spring-data-commons-2.1.6.RELEASE.jar;E:\maven\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-test\2.1.4.RELEASE\spring-boot-starter-test-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-test\2.1.4.RELEASE\spring-boot-test-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-test-autoconfigure\2.1.4.RELEASE\spring-boot-test-autoconfigure-2.1.4.RELEASE.jar;E:\maven\repository\com\jayway\jsonpath\json-path\2.4.0\json-path-2.4.0.jar;E:\maven\repository\net\minidev\json-smart\2.3\json-smart-2.3.jar;E:\maven\repository\net\minidev\accessors-smart\1.2\accessors-smart-1.2.jar;E:\maven\repository\org\ow2\asm\asm\5.0.4\asm-5.0.4.jar;E:\maven\repository\org\assertj\assertj-core\3.11.1\assertj-core-3.11.1.jar;E:\maven\repository\org\mockito\mockito-core\2.23.4\mockito-core-2.23.4.jar;E:\maven\repository\net\bytebuddy\byte-buddy\1.9.12\byte-buddy-1.9.12.jar;E:\maven\repository\net\bytebuddy\byte-buddy-agent\1.9.12\byte-buddy-agent-1.9.12.jar;E:\maven\repository\org\objenesis\objenesis\2.6\objenesis-2.6.jar;E:\maven\repository\org\hamcrest\hamcrest-library\1.3\hamcrest-library-1.3.jar;E:\maven\repository\org\skyscreamer\jsonassert\1.5.0\jsonassert-1.5.0.jar;E:\maven\repository\com\vaadin\external\google\android-json\0.0.20131108.vaadin1\android-json-0.0.20131108.vaadin1.jar;E:\maven\repository\org\springframework\spring-core\5.1.6.RELEASE\spring-core-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-jcl\5.1.6.RELEASE\spring-jcl-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-test\5.1.6.RELEASE\spring-test-5.1.6.RELEASE.jar;E:\maven\repository\org\xmlunit\xmlunit-core\2.6.2\xmlunit-core-2.6.2.jar;E:\maven\repository\org\mongodb\mongodb-driver\3.8.2\mongodb-driver-3.8.2.jar;E:\maven\repository\org\mongodb\bson\3.8.2\bson-3.8.2.jar;E:\maven\repository\org\mongodb\mongodb-driver-core\3.8.2\mongodb-driver-core-3.8.2.jar;E:\maven\repository\org\junit\platform\junit-platform-launcher\1.3.2\junit-platform-launcher-1.3.2.jar;E:\maven\repository\org\junit\jupiter\junit-jupiter-engine\5.3.2\junit-jupiter-engine-5.3.2.jar;E:\maven\repository\org\junit\jupiter\junit-jupiter-api\5.3.2\junit-jupiter-api-5.3.2.jar;E:\maven\repository\org\springframework\boot\spring-boot-configuration-processor\2.1.4.RELEASE\spring-boot-configuration-processor-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-devtools\2.1.4.RELEASE\spring-boot-devtools-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot\2.1.4.RELEASE\spring-boot-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.4.RELEASE\spring-boot-autoconfigure-2.1.4.RELEASE.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit5 com.zsx.test.repositoty.CustomerRepositoryTest,testSave
23:10:56.241 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
23:10:56.264 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
23:10:56.296 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.zsx.test.repositoty.CustomerRepositoryTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
23:10:56.311 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.zsx.test.repositoty.CustomerRepositoryTest], using SpringBootContextLoader
23:10:56.315 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zsx.test.repositoty.CustomerRepositoryTest]: class path resource [com/zsx/test/repositoty/CustomerRepositoryTest-context.xml] does not exist
23:10:56.316 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zsx.test.repositoty.CustomerRepositoryTest]: class path resource [com/zsx/test/repositoty/CustomerRepositoryTestContext.groovy] does not exist
23:10:56.316 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.zsx.test.repositoty.CustomerRepositoryTest]: no resource found for suffixes {-context.xml, Context.groovy}.
23:10:56.317 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.zsx.test.repositoty.CustomerRepositoryTest]: CustomerRepositoryTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
23:10:56.362 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.zsx.test.repositoty.CustomerRepositoryTest]
23:10:56.491 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [F:\IdeaProjects\springbootmongodb\target\classes\com\zsx\MongoDBApplication.class]
23:10:56.496 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.zsx.MongoDBApplication for test class com.zsx.test.repositoty.CustomerRepositoryTest
23:10:56.698 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.zsx.test.repositoty.CustomerRepositoryTest]: using defaults.
23:10:56.698 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
23:10:56.718 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@3a5ecce3, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@561868a0, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@2ea6e30c, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@6138e79a, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2dcd168a, org.springframework.test.context.transaction.TransactionalTestExecutionListener@388526fb, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@21a21c64, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@7803bfd, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@42bc14c1, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@531f4093, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@62ef27a8, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@6436a7db]
23:10:56.722 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@5143c662 testClass = CustomerRepositoryTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@77825085 testClass = CustomerRepositoryTest, locations = '{}', classes = '{class com.zsx.MongoDBApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@72cc7e6f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@909217e, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@cecf639, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@359df09a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
23:10:56.764 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-07-04 23:10:57.626  INFO 12220 --- [           main] c.z.t.repositoty.CustomerRepositoryTest  : Starting CustomerRepositoryTest on zsx with PID 12220 (started by admin in F:\IdeaProjects\springbootmongodb)
2019-07-04 23:10:57.628  INFO 12220 --- [           main] c.z.t.repositoty.CustomerRepositoryTest  : No active profile set, falling back to default profiles: default
2019-07-04 23:10:59.189  INFO 12220 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-04 23:10:59.316  INFO 12220 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 117ms. Found 1 repository interfaces.
2019-07-04 23:11:01.408  INFO 12220 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-07-04 23:11:01.408  INFO 12220 --- [           main] org.mongodb.driver.cluster               : Adding discovered server localhost:27017 to client view of cluster
2019-07-04 23:11:01.482  INFO 12220 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:99}] to localhost:27017
2019-07-04 23:11:01.487  INFO 12220 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 10]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3300000}
2019-07-04 23:11:01.488  INFO 12220 --- [localhost:27017] org.mongodb.driver.cluster               : Discovered cluster type of STANDALONE
2019-07-04 23:11:01.838  INFO 12220 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-04 23:11:02.203  INFO 12220 --- [           main] c.z.t.repositoty.CustomerRepositoryTest  : Started CustomerRepositoryTest in 5.396 seconds (JVM running for 7.276)
2019-07-04 23:11:02.706  INFO 12220 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:100}] to localhost:27017
2019-07-04 23:11:02.742  INFO 12220 --- [       Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2019-07-04 23:11:02.744  INFO 12220 --- [       Thread-2] org.mongodb.driver.connection            : Closed connection [connectionId{localValue:2, serverValue:100}] to localhost:27017 because the pool has been closed.

Process finished with exit code 0

九、打开数据库查看结果

从结果可以看出集成MongoDB成功 

十、扩展:MongoTemplate使用

1. 在实体类Customer上加@Document("test_customer")注解,指定集合名字

@Document("test_customer")

2. 重新运行测试testSave方法,查看数据库结果 

package com.zsx.test.repositoty;

import com.zsx.entity.Customer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import static org.junit.Assert.assertNotNull;

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class MongoTemplateTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    void testFindById () {
        assertNotNull(mongoTemplate);
        Customer customer = mongoTemplate.findById("5d1e180ffbfab71abcc72e1a", Customer.class);
        System.out.println(customer);
        assertNotNull(customer);
    }
}

4. 运行测试方法testFindById

H:\JDK\jdk-11.0.3\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:H:\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=51767:H:\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath "H:\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar;H:\JetBrains\IntelliJ IDEA 2019.1.3\plugins\junit\lib\junit-rt.jar;H:\JetBrains\IntelliJ IDEA 2019.1.3\plugins\junit\lib\junit5-rt.jar;E:\maven\repository\org\junit\vintage\junit-vintage-engine\5.3.2\junit-vintage-engine-5.3.2.jar;E:\maven\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;E:\maven\repository\org\junit\platform\junit-platform-engine\1.3.2\junit-platform-engine-1.3.2.jar;E:\maven\repository\org\junit\platform\junit-platform-commons\1.3.2\junit-platform-commons-1.3.2.jar;E:\maven\repository\org\opentest4j\opentest4j\1.1.1\opentest4j-1.1.1.jar;E:\maven\repository\junit\junit\4.12\junit-4.12.jar;E:\maven\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;F:\IdeaProjects\springbootmongodb\target\test-classes;F:\IdeaProjects\springbootmongodb\target\classes;E:\maven\repository\org\springframework\boot\spring-boot-starter-web\2.1.4.RELEASE\spring-boot-starter-web-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter\2.1.4.RELEASE\spring-boot-starter-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-logging\2.1.4.RELEASE\spring-boot-starter-logging-2.1.4.RELEASE.jar;E:\maven\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;E:\maven\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;E:\maven\repository\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;E:\maven\repository\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;E:\maven\repository\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\maven\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;E:\maven\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-json\2.1.4.RELEASE\spring-boot-starter-json-2.1.4.RELEASE.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-tomcat\2.1.4.RELEASE\spring-boot-starter-tomcat-2.1.4.RELEASE.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.17\tomcat-embed-core-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.17\tomcat-embed-el-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.17\tomcat-embed-websocket-9.0.17.jar;E:\maven\repository\org\hibernate\validator\hibernate-validator\6.0.16.Final\hibernate-validator-6.0.16.Final.jar;E:\maven\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;E:\maven\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;E:\maven\repository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;E:\maven\repository\org\springframework\spring-web\5.1.6.RELEASE\spring-web-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-beans\5.1.6.RELEASE\spring-beans-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-webmvc\5.1.6.RELEASE\spring-webmvc-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-aop\5.1.6.RELEASE\spring-aop-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-context\5.1.6.RELEASE\spring-context-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-expression\5.1.6.RELEASE\spring-expression-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-data-mongodb\2.1.4.RELEASE\spring-boot-starter-data-mongodb-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-mongodb\2.1.6.RELEASE\spring-data-mongodb-2.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-tx\5.1.6.RELEASE\spring-tx-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-commons\2.1.6.RELEASE\spring-data-commons-2.1.6.RELEASE.jar;E:\maven\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-test\2.1.4.RELEASE\spring-boot-starter-test-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-test\2.1.4.RELEASE\spring-boot-test-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-test-autoconfigure\2.1.4.RELEASE\spring-boot-test-autoconfigure-2.1.4.RELEASE.jar;E:\maven\repository\com\jayway\jsonpath\json-path\2.4.0\json-path-2.4.0.jar;E:\maven\repository\net\minidev\json-smart\2.3\json-smart-2.3.jar;E:\maven\repository\net\minidev\accessors-smart\1.2\accessors-smart-1.2.jar;E:\maven\repository\org\ow2\asm\asm\5.0.4\asm-5.0.4.jar;E:\maven\repository\org\assertj\assertj-core\3.11.1\assertj-core-3.11.1.jar;E:\maven\repository\org\mockito\mockito-core\2.23.4\mockito-core-2.23.4.jar;E:\maven\repository\net\bytebuddy\byte-buddy\1.9.12\byte-buddy-1.9.12.jar;E:\maven\repository\net\bytebuddy\byte-buddy-agent\1.9.12\byte-buddy-agent-1.9.12.jar;E:\maven\repository\org\objenesis\objenesis\2.6\objenesis-2.6.jar;E:\maven\repository\org\hamcrest\hamcrest-library\1.3\hamcrest-library-1.3.jar;E:\maven\repository\org\skyscreamer\jsonassert\1.5.0\jsonassert-1.5.0.jar;E:\maven\repository\com\vaadin\external\google\android-json\0.0.20131108.vaadin1\android-json-0.0.20131108.vaadin1.jar;E:\maven\repository\org\springframework\spring-core\5.1.6.RELEASE\spring-core-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-jcl\5.1.6.RELEASE\spring-jcl-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-test\5.1.6.RELEASE\spring-test-5.1.6.RELEASE.jar;E:\maven\repository\org\xmlunit\xmlunit-core\2.6.2\xmlunit-core-2.6.2.jar;E:\maven\repository\org\mongodb\mongodb-driver\3.8.2\mongodb-driver-3.8.2.jar;E:\maven\repository\org\mongodb\bson\3.8.2\bson-3.8.2.jar;E:\maven\repository\org\mongodb\mongodb-driver-core\3.8.2\mongodb-driver-core-3.8.2.jar;E:\maven\repository\org\junit\platform\junit-platform-launcher\1.3.2\junit-platform-launcher-1.3.2.jar;E:\maven\repository\org\junit\jupiter\junit-jupiter-engine\5.3.2\junit-jupiter-engine-5.3.2.jar;E:\maven\repository\org\junit\jupiter\junit-jupiter-api\5.3.2\junit-jupiter-api-5.3.2.jar;E:\maven\repository\org\springframework\boot\spring-boot-configuration-processor\2.1.4.RELEASE\spring-boot-configuration-processor-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-devtools\2.1.4.RELEASE\spring-boot-devtools-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot\2.1.4.RELEASE\spring-boot-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.4.RELEASE\spring-boot-autoconfigure-2.1.4.RELEASE.jar" com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 -junit5 com.zsx.test.repositoty.MongoTemplateTest,testFindById
23:53:43.562 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
23:53:43.579 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
23:53:43.600 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.zsx.test.repositoty.MongoTemplateTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
23:53:43.611 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.zsx.test.repositoty.MongoTemplateTest], using SpringBootContextLoader
23:53:43.617 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zsx.test.repositoty.MongoTemplateTest]: class path resource [com/zsx/test/repositoty/MongoTemplateTest-context.xml] does not exist
23:53:43.617 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zsx.test.repositoty.MongoTemplateTest]: class path resource [com/zsx/test/repositoty/MongoTemplateTestContext.groovy] does not exist
23:53:43.618 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.zsx.test.repositoty.MongoTemplateTest]: no resource found for suffixes {-context.xml, Context.groovy}.
23:53:43.619 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.zsx.test.repositoty.MongoTemplateTest]: MongoTemplateTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
23:53:43.678 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.zsx.test.repositoty.MongoTemplateTest]
23:53:43.775 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [F:\IdeaProjects\springbootmongodb\target\classes\com\zsx\MongoDBApplication.class]
23:53:43.776 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.zsx.MongoDBApplication for test class com.zsx.test.repositoty.MongoTemplateTest
23:53:43.928 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.zsx.test.repositoty.MongoTemplateTest]: using defaults.
23:53:43.929 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
23:53:43.945 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@62ef27a8, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@6436a7db, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@460ebd80, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@6f3c660a, org.springframework.test.context.support.DirtiesContextTestExecutionListener@74f5ce22, org.springframework.test.context.transaction.TransactionalTestExecutionListener@25aca718, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@16fdec90, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@1afdd473, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@40238dd0, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@7776ab, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@79179359, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@dbd8e44]
23:53:43.950 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@4f25b795 testClass = MongoTemplateTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@6fb365ed testClass = MongoTemplateTest, locations = '{}', classes = '{class com.zsx.MongoDBApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@5e2c3d18, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5b218417, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@5890e879, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1972e513], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
23:53:44.016 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-07-04 23:53:44.595  INFO 13604 --- [           main] c.zsx.test.repositoty.MongoTemplateTest  : Starting MongoTemplateTest on zsx with PID 13604 (started by admin in F:\IdeaProjects\springbootmongodb)
2019-07-04 23:53:44.598  INFO 13604 --- [           main] c.zsx.test.repositoty.MongoTemplateTest  : No active profile set, falling back to default profiles: default
2019-07-04 23:53:46.130  INFO 13604 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-04 23:53:46.212  INFO 13604 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 72ms. Found 1 repository interfaces.
2019-07-04 23:53:48.048  INFO 13604 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-07-04 23:53:48.048  INFO 13604 --- [           main] org.mongodb.driver.cluster               : Adding discovered server localhost:27017 to client view of cluster
2019-07-04 23:53:48.113  INFO 13604 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:103}] to localhost:27017
2019-07-04 23:53:48.118  INFO 13604 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 10]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3159556}
2019-07-04 23:53:48.119  INFO 13604 --- [localhost:27017] org.mongodb.driver.cluster               : Discovered cluster type of STANDALONE
2019-07-04 23:53:48.418  INFO 13604 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-04 23:53:48.756  INFO 13604 --- [           main] c.zsx.test.repositoty.MongoTemplateTest  : Started MongoTemplateTest in 4.729 seconds (JVM running for 6.508)
2019-07-04 23:53:49.361  INFO 13604 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:104}] to localhost:27017
Customer[id=5d1e180ffbfab71abcc72e1a, firstName='zhangsan', lastName='zhangsanfeng']
2019-07-04 23:53:49.400  INFO 13604 --- [       Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2019-07-04 23:53:49.401  INFO 13604 --- [       Thread-2] org.mongodb.driver.connection            : Closed connection [connectionId{localValue:2, serverValue:104}] to localhost:27017 because the pool has been closed.

Process finished with exit code 0

 从结果看出MongoTemplate方式操作MongoDB成功

十一、扩展:GridFsTemplate使用

1. 创建保存数据类FileDao.java

package com.zsx.dao;

import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Repository
public class FileDao {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileDao.class);

    @Autowired
    private GridFsTemplate gridFsTemplate;

    public ObjectId save(MultipartFile multipartFile) {
        try {
            return gridFsTemplate.store(multipartFile.getInputStream(), multipartFile.getOriginalFilename(), multipartFile.getContentType());
        } catch (IOException e) {
            LOGGER.error("FileDao.save.IOException: " + e.getMessage());
        }
        return null;
    }

}

2. 创建业务数据处理接口FileService.java

package com.zsx.service;

import org.springframework.web.multipart.MultipartFile;

public interface FileService {
    boolean save(MultipartFile multipartFile);
}

3. 创建业务接口实现FileServiceImpl.java

package com.zsx.service.impl;

import com.zsx.dao.FileDao;
import com.zsx.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileDao fileDao;

    @Override
    public boolean save(MultipartFile multipartFile) {
        if(fileDao.save(multipartFile) == null) {
            return false;
        }
        return true;
    }
}

4. 编写api接口

package com.zsx.api;

import com.zsx.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/file")
    public ResponseEntity save(MultipartFile multipartFile) {
        if (multipartFile == null) {
            return new ResponseEntity("The input parameter is invalid", HttpStatus.BAD_REQUEST);
        }
        if (fileService.save(multipartFile)) {
            return new ResponseEntity("success", HttpStatus.OK);
        }
        return new ResponseEntity("fail", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

5. 启动引导类MongoDBApplication.java主程序

H:\JDK\jdk-11.0.3\bin\java.exe -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:H:\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=52878:H:\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath F:\IdeaProjects\springbootmongodb\target\classes;E:\maven\repository\org\springframework\boot\spring-boot-starter-web\2.1.4.RELEASE\spring-boot-starter-web-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter\2.1.4.RELEASE\spring-boot-starter-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-logging\2.1.4.RELEASE\spring-boot-starter-logging-2.1.4.RELEASE.jar;E:\maven\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;E:\maven\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;E:\maven\repository\org\apache\logging\log4j\log4j-to-slf4j\2.11.2\log4j-to-slf4j-2.11.2.jar;E:\maven\repository\org\apache\logging\log4j\log4j-api\2.11.2\log4j-api-2.11.2.jar;E:\maven\repository\org\slf4j\jul-to-slf4j\1.7.26\jul-to-slf4j-1.7.26.jar;E:\maven\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;E:\maven\repository\org\yaml\snakeyaml\1.23\snakeyaml-1.23.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-json\2.1.4.RELEASE\spring-boot-starter-json-2.1.4.RELEASE.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;E:\maven\repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.8\jackson-datatype-jdk8-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.8\jackson-datatype-jsr310-2.9.8.jar;E:\maven\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.8\jackson-module-parameter-names-2.9.8.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-tomcat\2.1.4.RELEASE\spring-boot-starter-tomcat-2.1.4.RELEASE.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.17\tomcat-embed-core-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.17\tomcat-embed-el-9.0.17.jar;E:\maven\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.17\tomcat-embed-websocket-9.0.17.jar;E:\maven\repository\org\hibernate\validator\hibernate-validator\6.0.16.Final\hibernate-validator-6.0.16.Final.jar;E:\maven\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;E:\maven\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;E:\maven\repository\com\fasterxml\classmate\1.4.0\classmate-1.4.0.jar;E:\maven\repository\org\springframework\spring-web\5.1.6.RELEASE\spring-web-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-beans\5.1.6.RELEASE\spring-beans-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-webmvc\5.1.6.RELEASE\spring-webmvc-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-aop\5.1.6.RELEASE\spring-aop-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-context\5.1.6.RELEASE\spring-context-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-expression\5.1.6.RELEASE\spring-expression-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-starter-data-mongodb\2.1.4.RELEASE\spring-boot-starter-data-mongodb-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-mongodb\2.1.6.RELEASE\spring-data-mongodb-2.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-tx\5.1.6.RELEASE\spring-tx-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\data\spring-data-commons\2.1.6.RELEASE\spring-data-commons-2.1.6.RELEASE.jar;E:\maven\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;E:\maven\repository\org\springframework\spring-core\5.1.6.RELEASE\spring-core-5.1.6.RELEASE.jar;E:\maven\repository\org\springframework\spring-jcl\5.1.6.RELEASE\spring-jcl-5.1.6.RELEASE.jar;E:\maven\repository\org\mongodb\mongodb-driver\3.8.2\mongodb-driver-3.8.2.jar;E:\maven\repository\org\mongodb\bson\3.8.2\bson-3.8.2.jar;E:\maven\repository\org\mongodb\mongodb-driver-core\3.8.2\mongodb-driver-core-3.8.2.jar;E:\maven\repository\org\springframework\boot\spring-boot-configuration-processor\2.1.4.RELEASE\spring-boot-configuration-processor-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-devtools\2.1.4.RELEASE\spring-boot-devtools-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot\2.1.4.RELEASE\spring-boot-2.1.4.RELEASE.jar;E:\maven\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.4.RELEASE\spring-boot-autoconfigure-2.1.4.RELEASE.jar com.zsx.MongoDBApplication

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-07-05 00:33:18.945  INFO 8060 --- [  restartedMain] com.zsx.MongoDBApplication               : Starting MongoDBApplication on zsx with PID 8060 (F:\IdeaProjects\springbootmongodb\target\classes started by admin in F:\IdeaProjects\springbootmongodb)
2019-07-05 00:33:18.954  INFO 8060 --- [  restartedMain] com.zsx.MongoDBApplication               : No active profile set, falling back to default profiles: default
2019-07-05 00:33:19.026  INFO 8060 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-07-05 00:33:19.026  INFO 8060 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-07-05 00:33:20.006  INFO 8060 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-05 00:33:20.069  INFO 8060 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 57ms. Found 1 repository interfaces.
2019-07-05 00:33:20.819  INFO 8060 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-05 00:33:20.844  INFO 8060 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-05 00:33:20.845  INFO 8060 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-07-05 00:33:20.853  INFO 8060 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : An older version [1.2.16] of the APR based Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [1.2.21]
2019-07-05 00:33:20.853  INFO 8060 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : Loaded APR based Apache Tomcat Native library [1.2.16] using APR version [1.6.3].
2019-07-05 00:33:20.853  INFO 8060 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2019-07-05 00:33:20.853  INFO 8060 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2019-07-05 00:33:21.939  INFO 8060 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.0.2m  2 Nov 2017]
2019-07-05 00:33:22.192  INFO 8060 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-05 00:33:22.193  INFO 8060 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3167 ms
2019-07-05 00:33:22.661  INFO 8060 --- [  restartedMain] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-07-05 00:33:22.661  INFO 8060 --- [  restartedMain] org.mongodb.driver.cluster               : Adding discovered server localhost:27017 to client view of cluster
2019-07-05 00:33:22.705  INFO 8060 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:105}] to localhost:27017
2019-07-05 00:33:22.710  INFO 8060 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 10]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=2821777}
2019-07-05 00:33:22.711  INFO 8060 --- [localhost:27017] org.mongodb.driver.cluster               : Discovered cluster type of STANDALONE
2019-07-05 00:33:22.835  INFO 8060 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2019-07-05 00:33:23.135  INFO 8060 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-05 00:33:23.395  INFO 8060 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-05 00:33:23.399  INFO 8060 --- [  restartedMain] com.zsx.MongoDBApplication               : Started MongoDBApplication in 4.981 seconds (JVM running for 6.216)

6. 打开postman,发送请求http://localhost:8080/api/file

7. 打开数据库,查看结果

从结果可以看出保存文件成功

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值