I’m trying to connect my Spring Boot application to MongoDB Atlas, but I’m encountering the following error:
Caused by: java.lang.IllegalArgumentException: 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.
My application.properties file:
spring.application.name=movies
spring.data.mongodb.database=${env.MONGO_DATABASE}
spring.data.mongodb.uri=mongodb+srv://${env.MONGO_USER}:${env.MONGO_PASSWORD}@${env.MONGO_CLUSTER}
My .env file:
MONGO_USER=myUsername
MONGO_PASSWORD=Otek15767%2AGIRL2
MONGO_DATABASE=moviesdb
MONGO_CLUSTER=cluster0.mongodb.net
I have encoded the special character (*) in my password as %2A. However, I’m still encountering the SRV hostname error.
My dependencies in pom.xml:
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>me.paulschwarz</groupId>
<artifactId>spring-dotenv</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
What I’ve Tried:
Verified the Connection String:
Copied the connection string from MongoDB Atlas.
Replaced placeholders with the environment variables.
Encoded Special Characters:
Encoded the * in the password as %2A.
Validated Environment Variables:
Confirmed that MONGO_CLUSTER is set to cluster0.mongodb.net.
Restarted the Application:
Ensured the application picks up the latest .env values.
How do I resolve this
2
Answers
Managed to resolve it by removing the env in application properties and having:
Try bypassing the application properties by adding the following directly to .env
This uses the Spring Boot mechanism for picking up application.properties values from env vars