181

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
  • 11,041
  • 17
  • 71
  • 110

4 Answers4

237

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

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
Dave Syer
  • 56,583
  • 10
  • 155
  • 143
  • 2
    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
  • @IgorDonin you can just prefix the command with an assignment to the environment variable. For example: ```OPENSHIFT_DIY_PORT=1234 java -jar myapp.jar``` – dsharp Mar 06 '23 at 18:45
144

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

logging:
  level:
    root: ${LOGGING_LEVEL_ROOT:info}
Oleksandr Yefymov
  • 6,081
  • 2
  • 22
  • 32
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
  • 1,374
  • 12
  • 17
0

The answer is already given. You can use your IDE like IntelliJ to provide the env variables, you can do that as the following

enter image description here

enter image description here

enter image description here

Smaillns
  • 2,540
  • 1
  • 28
  • 40