无法将 Spring Boot 与 MongoDb 连接

Posted

技术标签:

【中文标题】无法将 Spring Boot 与 MongoDb 连接【英文标题】:Can't connect Spring boot with MongoDb 【发布时间】:2021-06-06 02:19:53 【问题描述】:

我正在尝试在 Spring Boot 2.3.9 中使用 Spring Boot 与 MongoDB 一起制作一个简单的程序 从启动日志中我怀疑有问题,好像初始化了两次。

这是我的控制台输出:

2021-03-08 01:54:43.515  INFO 26609 --- [  restartedMain] c.a.a.r.SpringbootRegistroApplication    : Starting SpringbootRegistroApplication on santiagoVB with PID 26609 (/home/santiago/Documentos/workspace/springboot-registro/target/classes started by santiago in /home/santiago/Documentos/workspace/springboot-registro)
2021-03-08 01:54:43.521  INFO 26609 --- [  restartedMain] c.a.a.r.SpringbootRegistroApplication    : No active profile set, falling back to default profiles: default
2021-03-08 01:54:43.680  INFO 26609 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-03-08 01:54:43.682  INFO 26609 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-03-08 01:54:45.719  INFO 26609 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-03-08 01:54:45.895  INFO 26609 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 167ms. Found 1 MongoDB repository interfaces.
2021-03-08 01:54:46.683  INFO 26609 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-03-08 01:54:46.699  INFO 26609 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-03-08 01:54:46.701  INFO 26609 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.43]
2021-03-08 01:54:46.830  INFO 26609 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-03-08 01:54:46.830  INFO 26609 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3147 ms
2021-03-08 01:54:47.152  INFO 26609 --- [  restartedMain] org.mongodb.driver.cluster               : Cluster created with settings hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'
2021-03-08 01:54:47.363  INFO 26609 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionIdlocalValue:1, serverValue:12] to localhost:27017
2021-03-08 01:54:47.372  INFO 26609 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescriptionaddress=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=9, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=5581801
2021-03-08 01:54:47.714  INFO 26609 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2021-03-08 01:54:48.326  INFO 26609 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-03-08 01:54:48.685  INFO 26609 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-03-08 01:54:48.701  INFO 26609 --- [  restartedMain] c.a.a.r.SpringbootRegistroApplication    : Started SpringbootRegistroApplication in 6.21 seconds (JVM running for 9.239)

我的 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.9.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.appcity.app.registro</groupId>
    <artifactId>springboot-registro</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-registro</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>15</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-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <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>
    </dependencies>

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

</project>

我的 application.properties:

spring.data.mongodb.uri=mongodb://localhost:27017/App
spring.data.mongodb.auto-index-creation=true
#spring.data.mongodb.host=localhost
#spring.data.mongodb.port=27017
#spring.data.mongodb.username=Udea
#spring.data.mongodb.password=udeapp
#spring.data.mongodb.database=App

我的对象:

package com.appcity.app.registro.models.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "UsuarioDb")
public class UsuarioDb 

    @Id
    private String id;
    private String username;
    private String phone;
    private String email;
    private String password;

    public UsuarioDb() 
        super();
    

    public UsuarioDb(String id, String username, String phone, String email, String password) 
        super();
        this.id = id;
        this.username = username;
        this.phone = phone;
        this.email = email;
        this.password = password;
    

    public String getId() 
        return id;
    

    public void setId(String id) 
        this.id = id;
    

    public String getUsername() 
        return username;
    

    public void setUsername(String username) 
        this.username = username;
    

    public String getPhone() 
        return phone;
    

    public void setPhone(String phone) 
        this.phone = phone;
    

    public String getEmail() 
        return email;
    

    public void setEmail(String email) 
        this.email = email;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    

    @Override
    public String toString() 
        return "UsuarioDb [id=" + id + ", username=" + username + ", phone=" + phone + ", email=" + email
                + ", password=" + password + "]";
    


我的界面:

package com.appcity.app.registro.models.dao;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.appcity.app.registro.models.entity.UsuarioDb;

@Repository
public interface RegistroDao extends MongoRepository<UsuarioDb, String>


我的控制器:

package com.appcity.app.registro.controllers;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.appcity.app.registro.models.dao.RegistroDao;
import com.appcity.app.registro.models.entity.UsuarioDb;

//@CrossOrigin
@RestController
public class RegistroController 
    
    @Autowired
    private RegistroDao repository;

    @PostMapping("/registro/crear")
    public String saveUsuarioDb(@RequestBody UsuarioDb usuarioDb) 
        repository.save(usuarioDb);
        return "Added usuarioDb with id : " + usuarioDb.getId();
    

    @GetMapping("/registro/listar")
    public List<UsuarioDb> getUsers()
        return repository.findAll();
    
    
    @GetMapping("/registro/listar/id")
    public Optional<UsuarioDb> getUser(@PathVariable String id)
        return repository.findById(id);
    
    
    @DeleteMapping("/registro/eliminar/id")
    public String deleteUser(@PathVariable String id) 
        repository.deleteById(id);
        return "usuarioDb deleted with id : "+id;
    

我在 Ubuntu 中的 MongoDb 状态:

● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2021-03-08 00:30:58 -05; 1h 46min ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 21445 (mongod)
     Memory: 160.1M
     CGroup: /system.slice/mongod.service
             └─21445 /usr/bin/mongod --config /etc/mongod.conf

mar 08 00:30:58 santiagoVB systemd[1]: Started MongoDB Database Server.

我在 MongoDb 中的数据库:

show dbs
App     0.000GB
admin   0.000GB
config  0.000GB
local   0.000GB

我做错了什么? 我有什么配置错误?

【问题讨论】:

为什么你认为没有连接?我在您的日志中看不到任何错误 因为映射到[/]的servlet dispatcherServlet 并且没有创建映射过滤器,所以我用postman做测试,程序运行但没有在mongo集合中创建任何文档 你得到什么http返回码? 在RegistroController中添加ResponseStatus和Postman Return 201 Created 您是否可以使用 Spring Boot CommandLineRunner 中的存储库方法并查看任何结果? 【参考方案1】:

我遇到了类似的问题,我安装了不同的 JDK 补丁。我有 JDK 11.0.2,我将其更改为 JDK 11.0.10,它对我有用。

另外,您需要有 @CrossOrigin(origins = "*") 注释。 *(星号)表示您允许来自任何来源的请求。

【讨论】:

你能指定哪一个吗? edit 提供所有相关信息的答案会有所帮助

以上是关于无法将 Spring Boot 与 MongoDb 连接的主要内容,如果未能解决你的问题,请参考以下文章

无法将我的spring-boot应用程序与mongodb云图集连接起来

尝试将 Spring Boot 应用程序与 mongoDB 连接时出错

无法在 Spring Boot 应用程序中连接到 MongoDB

无法使用 Hibernate 在 Spring Boot 中将 MongoDB 设置为自动递增

无法在多文档事务中创建命名空间(MongoDB 4.0、Spring Data 2.1.0、Spring Boot)

无法在 Docker-Compose 中使用 Spring Boot 连接到 MongoDB