Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly connect to MongoDB with Spring?

I'm total beginner in Spring. I want to create simple Spring app connecting to MongoDB. I generated Spring Boot with Spring Initializer and I created necessery files following a guide.

MongoDB is working. When I run the app I got the following error:

SpringFramework 2.2.0 M3 MongoDB 4.0 Dependencies (chosen in Spring Initializer): Web, MongoDB

DatabaseConfiguration.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
like image 693
Emil Mordarski Avatar asked May 29 '19 22:05

Emil Mordarski


People also ask

Is MongoDB good with spring boot?

Spring Boot is the easiest way to spin a spring project quickly and MongoDB is the most popular NoSQL database. Let's see how to integrate spring with MongoDB database.

Which annotation is used to link a MongoDB document with a spring bean?

The @Id annotation tells the mapper which property you want to use for the MongoDB _id property and the @Indexed annotation tells the mapping framework to call ensureIndex on that property of your document, making searches faster.


3 Answers

@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**

}

::Solution::

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;
}

}

specify mongodb uri in application.propeties as below::

spring.data.mongodb.uri=mongodb://username:password@localhost:27017/yourDB
like image 144
kunal kumar Avatar answered Oct 17 '22 11:10

kunal kumar


I believe the key to the answer is towards the end of the stack trace where it says:

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

Check that the host + ":" + port passed in the MongoClients.create method begins with either mongodb:// or mongodb+srv://. By looking at what you've posted, I can't tell what the host value is.

like image 26
jkcrump Avatar answered Oct 17 '22 10:10

jkcrump


If you are not sure about mongodb uri just delete "spring.data.mongodb.uri" property from application.properties. It should work.

like image 1
Nilesh Avatar answered Oct 17 '22 12:10

Nilesh