spring-bootmavenenvironment-variablesyaml

Pass environment variables to Spring Boot application with Maven


I am using Spring Boot 3.2.1.

I don't want to put sensitive data at config file as application.yml. So they are referring to environment variables.

Execution works fine at IntelliJ configuration settings for application (at Environment variables section).

However, it fails for maven execution from the console:

./mvnw -Ddemo-api-key=all56 -Ddemo-host=https://demo.api spring-boot:run

Here is exception details:

java.lang.IllegalArgumentException: Not enough variable values available to expand 'demo-host'
        at org.springframework.web.util.UriComponents$VarArgsTemplateVariables.getValue(UriComponents.java:367) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        at org.springframework.web.util.UriComponents.expandUriComponent(UriComponents.java:262) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        at org.springframework.web.util.HierarchicalUriComponents$PathSegmentComponent.expand(HierarchicalUriComponents.java:960) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:434) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        at org.springframework.web.util.HierarchicalUriComponents.expandInternal(HierarchicalUriComponents.java:52) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
        at org.springframework.web.util.UriComponents.expand(UriComponents.java:172) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]

Here is a snippet from application.yml:

car-parks-url: ${demo-host}/cap-ws/getCarParks?apiKey=${demo-api-key}

If I will put it higher at application.yml it works fine:

demo-api-key: all56
demo-host: https://demo.api

URL is formed correctly and all data are pulled fine.

Could not understand what is missed for passing it as the environment variables with maven?


Solution

  • It's not the same as:

    java -jar -Ddemo-api-key=all56 -Ddemo-host=https://demo.api myApp.jar
    

    Where you are passing env vars directly to your application.

    If you do:

    ./mvnw -Ddemo-api-key=all56 \
    -Ddemo-host=https://demo.api spring-boot:run
    

    You are passing the vars to maven task and not to the application.

    You could use:

     ./mvnw  spring-boot:run \
     -Dspring-boot.run.arguments="--demo-host=https://demo.api --demo-api-key=all56"
    

    or

     ./mvnw  spring-boot:run -Dspring-boot.run.jvmArguments="\
     -Ddemo-host=https://demo.api -Ddemo-api-key=all56"
    

    Those commands indicate that you what to pass those vars to Spring Boot application.

    Additional resource: