Search code examples
cloud-foundry

Accessing user provided env variables in cloudfoundry in Spring Boot application


I have the following user provided env variable defined for my app hosted in cloudfoundry/pivotal webservices:

MY_VAR=test

I am trying to access like so:

System.getProperty("MY_VAR")

but I am getting null in return. Any ideas as to what I am doing wrong would be appreciated.


Solution

  • Environment variables and system properties are two different things. If you set an environment variable with cf set-env my-app MY_VAR test then you would retrieve it in Java with System.getenv("MY_VAR"), not with System.getProperty.

    A better option is to take advantage of the Spring environment abstraction with features like the @Value annotation. As shown in the Spring Boot documentation, this allows you to specify values that get injected into your application as environment variables, system properties, static configuration, or external configuration without the application code explicitly retrieving the value.

    Note: You'll have to restage your application for your app instances to pick up the new env var.