process.env.dev

Environment Variables in Java

System.getenv() and Spring Boot properties

Reading Environment Variables

Java provides environment variable access through System.getenv(). This method returns an unmodifiable Map<String, String> of all variables, or a single value by name:

java
String dbUrl = System.getenv("DATABASE_URL");
String port = System.getenv().getOrDefault("PORT", "3000");

Java also has System.getProperty() for JVM system properties, which are separate from environment variables. System properties are set with -D flags and are often used by frameworks like Spring Boot.

Setting Environment Variables

Set variables in the shell before launching the JVM. Java does not provide a standard API to modify environment variables at runtime — System.getenv() returns an unmodifiable map.

bash
export DATABASE_URL=postgres://localhost/mydb
java -jar app.jar

Popular Libraries

Spring Boot automatically reads environment variables and maps them to configuration properties. A variable like SPRING_DATASOURCE_URL maps to spring.datasource.urlusing relaxed binding. Spring also supports .env files via the spring-dotenv library.

dotenv-java provides .env file support for non-Spring applications. It loads variables at startup and makes them available through its own API.

Common Gotchas

  • Environment variables are immutable in Java. You cannot set or modify them after the JVM starts.
  • Do not confuse environment variables (System.getenv) with system properties (System.getProperty). They are entirely separate namespaces.
  • In containerized deployments, use JAVA_OPTS or JAVA_TOOL_OPTIONS to pass JVM flags via environment variables.