Run mvn spring-boot:run With Environment Variables

Overview

Recently, my development laptop with 16 GB of RAM doesn’t seem to be enough to handle Intellij IDEA and WebStorm. So I had to remove WebStorm and use VSCode. Things got a little bit better but Intellij IDEA RAM usage kept going up.

Since I only need to work on the front end at this point, having Intellij IDEA running is optional and I still need about 3 GB of RAM for it.

Then I decided to find a way to run my Spring boot app with the Maven Spring Boot plugin (without using IDEA).

However, I have a file called local.env where I load all the environment variables.

Thus, typing mvn spring-boot:run doesn’t work for me because the environment variables are not loaded.

Here comes the solution!

Running spring boot app in command line with environment variables

Here is the content of my local.env file:

MONGO_HOST=localhost
MONGO_PORT=27017
MONGO_DB=ukata
MONGO_USER=mongo99
MONGO_PASSWORD=mongo99

It turned out that loading all the environment variables in this file is quite simple:

set -a; . ./src/main/resources/deployment/local.env; set +a; mvn spring-boot:run

And that’s enough to make the spring boot app run in the terminal:

Spring boot run with maven plugin and load the environment variables.

If you are on Windows, you will need to create a ps1 script to load the env:

Get-Content PATH_TO_local.env | ForEach-Object {
    $key, $value = $_.Split('=')
    [System.Environment]::SetEnvironmentVariable($key, $value, [System.EnvironmentVariableTarget]::Process)
}

Store it as load-env.ps1 (or any name you like) then run:

.\load-env.ps1; mvn spring-boot:run

Conclusion

In this post, I’ve shown you how to run your spring boot app with environment variables in the terminal so you can save some precious RAM for your other apps.

Leave a Comment