繁体   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