0

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.

user3105453
  • 1,881
  • 5
  • 32
  • 55

1 Answers1

1

You should use profiles to do that.

Read about profiles

Read how to use Profiles

How to Set Profiles

Ekansh Rastogi
  • 2,418
  • 2
  • 14
  • 23
  • Wonderful, thank you very much. I use `SPRING_PROFILES_ACTIVE=dev` locally and `SPRING_PROFILES_ACTIVE=prod` in the cloud. `application-dev.properties` and `application-prod.properties` both have `spring.data.mongodb.uri` declared but point to different instances. That's exactly what I was looking for. Thanks again! – user3105453 Jul 19 '16 at 15:12