Spring boot set environment variable programmatically

To set an environment variable programmatically in a Spring Boot application, you can use the SpringApplication.setDefaultProperties() method. This method allows you to set default properties for your application, including environment variables.

Here is an example of how you can use this method to set an environment variable:

<div id="example">
    <script type="text/javascript">
      document.getElementById("example").innerHTML = "Example Code";
    </script>
  </div>

In this example, we are setting an environment variable named “my.variable” with the value “my value”. This variable will be available to the application through the System.getenv() method.

You can place this code in your application’s main method, before calling SpringApplication.run(). Here is an example:

public static void main(String[] args) {
    SpringApplication.setDefaultProperties(Collections.singletonMap("my.variable", "my value"));
    SpringApplication.run(YourApplication.class, args);
}

Now, when your application starts up, it will have access to the environment variable “my.variable” with the value “my value”. You can access this variable anywhere in your application using System.getenv("my.variable").

Read more

Leave a comment