In this post under DotEnv, I will show with example the purpose of “systemProperties” method available in DotEnv framework.
With the help of this method whatever properties you read from .env file can be added as System properties and accessible using “System.getProperty()” method.
Below is the main class showing how to use it
Main class
package defaultPackage;
import io.github.cdimascio.dotenv.Dotenv;
public class Example8 {
public static void main(String[] args) {
Dotenv dotenv = Dotenv.load();
String result = dotenv.get("MY_ENV_VAR1");
System.out.println("Retrieved from dotenv MY_ENV_VAR1: " + result);
result = System.getProperty("MY_ENV_VAR1");
System.out.println("Retrieved from system properties first time MY_ENV_VAR1: " + result);
dotenv = Dotenv.configure().systemProperties().load();
result = System.getProperty("MY_ENV_VAR1");
System.out.println("Retrieved from system properties second time MY_ENV_VAR1: " + result);
}
}
At line 7, I called static “load” method on “Dotenv” class. It loaded the environment properties from .env file.
Next at line 8, I access the value of “MY_ENV_VAR1” using “dotenv” instance.
At line 11, I try to access the value of “MY_ENV_VAR1” using “System” class static method “getProperty” but it will return null.
At line 14, I create another instance of “Dotenv” but instead of just calling “load”, I try to configure it differently by calling “configure” method.
Using method chaining, I also call “systemProperties” method available on “DotenvBuilder”.
By calling this method we are instructing Dotenv to load properties in .env file as system properties. Then we call “load” method.
At line 15, I try to access the value of “MY_ENV_VAR1” using “System” static method “getProperty” and it will return the value.
In this way we can use “systemProperties” method.
Below is the output
Output
Retrieved from dotenv MY_ENV_VAR1: some_value1
Retrieved from system properties first time MY_ENV_VAR1: null
Retrieved from system properties second time MY_ENV_VAR1: some_value1