Search code examples
javaspringmongodbspring-boot

Error with SRV Host Name in Spring Boot MongoDB Configuration using .env file


I am referring to this video: Spring Boot + MongoDB | Crash Course

While storing the information about the URI in a .env file, it's giving the following error:

An SRV host name '${env.MONGO_CLUSTER}' was provided that does not contain at least three parts. It must contain a hostname, domain name and a top level domain.

All the information in the .env file is correct:

MONGO_DATABASE='movies-api-db'
MONGO_USER='LoKi'
MONGO_PASSWORD='****************'
MONGO_CLUSTER='cluster0.bubp9pu.mongodb.net'

And I have also added the dependency:

<dependency>
    <groupId>me.paulschwarz</groupId>
    <artifactId>spring-dotenv</artifactId>
    <version>4.0.0</version>
</dependency>

in the pom.xml file.

My application.properties file looks like this:

spring.data.mongodb.database=${env.MONGO_DATABASE}
spring.data.mongodb.uri=mongodb+srv://${env.MONGO_USER}:${env.MONGO_PASSWORD}@${env.MONGO_CLUSTER}

Where am I going wrong?

In the video, it's at: (0:44:48) Setting Up Environment Variables.

Things I have tried:

  • Verified the .env file for correct values.
  • Ensured that the .env file is in the root directory of the project.
  • Checked the environment variables by printing them out in the application.

I also tried the solution to this question, but then I got the following error:

com.mongodb.MongoConfigurationException: Failed looking up SRV record for '_mongodb._tcp.'cluster0.bubp9pu.mongodb.net''.

and

Caused by: javax.naming.NameNotFoundException: DNS name not found [response code 3]

Any help would be appreciated!


Solution

  • I finally found the answer! These are the points which caused it:

    1. In the .env file I had used '' instead of "". (Some parsers or tools used to load environment variables might interpret single quotes differently or not support them at all.)

    2. The link which I have provided for "What I have tried" is totally correct. I wasn't sure about using "" in the .env file so thought this answer was not working!