163

I tried using env variables in my application.yml configration like:

spring:
  main:
    show_banner: false

---

spring:
  profiles: production
server:
  address: $OPENSHIFT_DIY_IP
  port: $OPENSHIFT_DIY_PORT

but the env variables are not resolved. Do I have to provide a different notation?

In Rails you can e.g. use <%= ENV['FOOVAR'] %>

The only alternative is to run the app like:

java -jar my.jar --server.address=$OPENSHIFT_DIY_IP --server.port=$OPENSHIFT_DIY_PORT
Marcel Overdijk
  • 10,272
  • 16
  • 62
  • 105

3 Answers3

213

Try ${OPENSHIFT_DIY_PORT} (the usual Spring placeholder notation). See here for docs.

Andy Wilkinson
  • 97,688
  • 22
  • 237
  • 223
Dave Syer
  • 54,455
  • 10
  • 152
  • 139
  • 1
    This was exactly what I needed: `app.name=MyApp app.description=${app.name} is a Spring Boot application` – jurassix Apr 24 '18 at 16:49
  • 7
    Just to point out - if you're using kotlin, you need to put your reference in quotes & escape the `$` eg `root: "\${LOGGING_LEVEL_ROOT:info}"` – Edward Feb 11 '19 at 12:57
  • Guys, how can we go about passing the OPENSHIFT_DIY_PORT through unix cli when starting the application? I know we can use -D to pass override parameters, but does that also work for env variables? Ex.: nohup java -Xmx1024m -jar -Dspring.profiles.active="whatever". Is there a way to do that with env vars? – Igor Donin Feb 15 '19 at 12:06
  • 2
    @IgorDonin, would concatenation of variable assignments and program call an option for you? E. g.: `$MY_ENV=value && java -jar ...` – PAX May 12 '20 at 12:31
127

You even can add default value, if environment variable not provided:

logging:
  level:
    root: ${LOGGING_LEVEL_ROOT:info}
Oleksandr Yefymov
  • 5,080
  • 2
  • 19
  • 30
0

In summary YES. You can use the @Value to load the environment variables from the application.yml or application.properties

Additionally, you can load variables and cast them automatically if you need different data types to perform your validations and business logic.

server:
  address: ${OPENSHIFT_DIY_IP}
  port: ${OPENSHIFT_DIY_PORT}

Load information

@Value("${server.address}")
private String serverAddress;

@Value("${server.port}")
private Integer serverPort;
Jorge Tovar
  • 417
  • 4
  • 13