user3105453
user3105453

Reputation: 1981

Configure Spring Boot application to use MongoDB connection uri provided in environment variable

I would like to configure the connection-uri to my MongoDB through an environment variable. This way, I can set different values on localhost or if the Spring Boot application is running in a cloud.

I have included mongodb in my build.gradle file:

dependencies {
    compile 'org.springframework.cloud:spring-cloud-spring-service-connector:1.2.2.RELEASE'
    compile("org.springframework.boot:spring-boot-starter-data-mongodb")
    ...
}

To work locally, I have currently set the spring.data.mongodb.uri=mongodb://... in applications.properties but I would rather like to have that value read from an environment variable. How can I achieve this?

I have read articles about Spring Boot and Cloud suggesting extending the AbstractCloudConfig somehow like this:

public class CloudConfig extends AbstractCloudConfig {

    @Bean
    public MongoDbFactory documentMongoDbFactory() {
        return connectionFactory().mongoDbFactory();
    }

}

But I assume this wouldn't work with environment variables and working locally.

Upvotes: 0

Views: 742

Answers (1)

Ekansh Rastogi
Ekansh Rastogi

Reputation: 2536

You should use profiles to do that.

Read about profiles

Read how to use Profiles

How to Set Profiles

Upvotes: 1

Related Questions