簡體   English   中英

如何使用 Spring 正確連接到 MongoDB?

[英]How to properly connect to MongoDB with Spring?

我是春天的初學者。 我想創建連接到 MongoDB 的簡單 Spring 應用程序。 我使用 Spring Initializer 生成了 Spring Boot,並按照指南創建了必要的文件。

MongoDB 正在運行。 當我運行該應用程序時,出現以下錯誤:

SpringFramework 2.2.0 M3 MongoDB 4.0 依賴項(在 Spring Initializer 中選擇):Web、MongoDB

數據庫配置.java

package com.talkingflashcards.server.TalkingFlashcards.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@EnableMongoRepositories(basePackages = "com.talkingflashcards.server.TalkingFlashcards.repository")

@Configuration
public class DatabaseConfiguration extends AbstractMongoClientConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private String port;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create(host + ":" + port);
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }
}

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2019-05-29 23:52:19.955 ERROR 10144 --- [           main] o.s.boot.SpringApplication               : Application run failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:868) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:404) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:319) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1275) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1263) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at com.talkingflashcards.server.TalkingFlashcards.TalkingFlashcardsApplication.main(TalkingFlashcardsApplication.java:14) [classes/:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 19 common frames omitted
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.resolveBeanReference(ConfigurationClassEnhancer.java:394) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:366) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoTemplate(AbstractMongoClientConfiguration.java:58) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoTemplate$3(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoTemplate(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 20 common frames omitted
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 43 common frames omitted
    Caused by: java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at com.mongodb.ConnectionString.<init>(ConnectionString.java:288) ~[mongodb-driver-core-3.11.0-beta3.jar:na]
        at com.mongodb.client.MongoClients.create(MongoClients.java:61) ~[mongodb-driver-3.11.0-beta3.jar:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration.mongoClient(DatabaseConfiguration.java:32) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoDbFactory(AbstractMongoClientConfiguration.java:71) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoDbFactory$2(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 44 common frames omitted

    Disconnected from the target VM, address: '127.0.0.1:60940', transport: 'socket'

    Process finished with exit code 1

我相信答案的關鍵在於堆棧跟蹤的末尾,它說:

java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://'

檢查MongoClients.create方法中傳遞的host + ":" + port是否以mongodb://mongodb+srv://開頭。 通過查看您發布的內容,我無法確定host值是什么。

如果您不確定 mongodb uri,只需從 application.properties 中刪除“spring.data.mongodb.uri”屬性。 它應該工作。

@Override
public MongoClient mongoClient() {
    return MongoClients.create(host + ":" + port); // Error
    // trying to connect to **localhost:27017** it should be of form 
    // **mongodb://localhost:27017/yourDB**

}

::解決方案::

package com.talkingflashcards.server.TalkingFlashcards.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@EnableMongoRepositories(basePackages = "com.talkingflashcards.server.TalkingFlashcards.repository")

@Configuration
public class DatabaseConfiguration extends AbstractMongoClientConfiguration {


@Value("${spring.data.mongodb.uri}")
public String mongoUri;

@Override
protected void configureClientSettings(MongoClientSettings.Builder builder) {
    // customization hook
    builder.applyConnectionString(new ConnectionString(mongoUri));
}

@Override
protected String getDatabaseName() {
    return database;
}

}

在 application.propeties 中指定 mongodb uri 如下:

spring.data.mongodb.uri=mongodb://username:password@localhost:27017/yourDB

使用 Spring Boot,您無需顯式配置 MongoDB 連接。 application.properties ,您只需要在 config 下面設置(使用 MongoDB 在本地)

spring.data.mongodb.uri=mongodb://localhost:27017/yourDB

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM