Java Environment Variables and Configuration
Java environment variables let you change how a program behaves without changing or rebuilding its code. The same JAR can talk to a test database on one server and the production database on another, just because each server sets different values. Java reads them with System.getenv(), and combines them with system properties and properties files to build the app's configuration.
This lesson starts with single variables, adds defaults, type conversion and validation, then covers system properties, properties files, per-environment profiles and secrets. It ends with a reusable AppConfig class that layers all of these sources. Every example was run with JDK 21.
Read Java Environment Variables With System.getenv
System.getenv(name) returns the value of one variable as a String, or null if it is not set.
public class ReadEnv {
public static void main(String[] args) {
// read single variables; null means "not set"
String userHome = System.getenv("HOME");
String appPort = System.getenv("APP_PORT");
String missing = System.getenv("NOT_DEFINED_ANYWHERE");
System.out.println("HOME = " + userHome);
System.out.println("APP_PORT = " + appPort);
System.out.println("missing = " + missing);
}
}
APP_PORT=9090 java ReadEnv.java
HOME = /home/asha
APP_PORT = 9090
missing = null
How it works:
APP_PORT=9090 java ...sets the variable for this one command.export APP_PORT=9090would set it for the rest of the terminal session.- Environment variables are always strings. Converting them to numbers or booleans is your job, as shown below.
- Names are case-sensitive on Linux and macOS (
APP_PORTandapp_portare different) but not on Windows. Use UPPER_SNAKE_CASE everywhere to avoid surprises.
Setting Environment Variables per Platform
| Where | Command |
|---|---|
| Linux / macOS, one command | APP_PORT=9090 java -jar app.jar |
| Linux / macOS, session | export APP_PORT=9090 |
| Windows PowerShell | $env:APP_PORT = "9090" |
| Windows Command Prompt | set APP_PORT=9090 |
| systemd service | Environment=APP_PORT=9090 or EnvironmentFile= |
| Docker | docker run -e APP_PORT=9090 ... or --env-file |
Note: A running Java program cannot change its own environment variables.
System.getenv()returns a read-only map, and callingputon it throwsUnsupportedOperationException.
Default Values and Required Variables
Most settings have a sensible default; a few, like a database URL, do not. Handle both cases explicitly.
import java.util.Map;
public class EnvDefaults {
static String required(String name) {
String value = System.getenv(name);
if (value == null || value.isBlank()) {
throw new IllegalStateException("Missing required environment variable: " + name);
}
return value;
}
public static void main(String[] args) {
Map<String, String> env = System.getenv();
String environment = env.getOrDefault("APP_ENV", "dev");
int port = Integer.parseInt(env.getOrDefault("APP_PORT", "8080"));
System.out.println("env=" + environment + ", port=" + port);
String databaseUrl = required("DB_URL"); // no sensible default exists
System.out.println("db=" + databaseUrl);
}
}
java EnvDefaults.java
APP_ENV=prod APP_PORT=9091 DB_URL=jdbc:postgresql://db:5432/courses java EnvDefaults.java
env=dev, port=8080
Exception in thread "main" java.lang.IllegalStateException: Missing required environment variable: DB_URL
at EnvDefaults.required(EnvDefaults.java:8)
at EnvDefaults.main(EnvDefaults.java:19)
env=prod, port=9091
db=jdbc:postgresql://db:5432/courses
How it works:
System.getenv()with no argument returns all variables as aMap<String, String>, sogetOrDefaultgives you a one-line default.required()fails fast: the app stops at startup with a clear message instead of crashing later with a confusingNullPointerExceptionon the first database call.
Convert Environment Variables to Numbers, Booleans and Durations
Parse each value once, at startup, and turn bad input into a clear error message.
import java.time.Duration;
public class TypedEnv {
static int intValue(String name, int defaultValue) {
String raw = System.getenv(name);
if (raw == null) return defaultValue;
try {
return Integer.parseInt(raw.trim());
} catch (NumberFormatException e) {
throw new IllegalArgumentException(name + " must be a whole number, got '" + raw + "'");
}
}
static boolean boolValue(String name, boolean defaultValue) {
String raw = System.getenv(name);
if (raw == null) return defaultValue;
return switch (raw.trim().toLowerCase()) {
case "true", "yes", "1", "on" -> true;
case "false", "no", "0", "off" -> false;
default -> throw new IllegalArgumentException(name + " must be true or false, got '" + raw + "'");
};
}
// accepts 500ms, 30s, 5m, 2h
static Duration durationValue(String name, Duration defaultValue) {
String raw = System.getenv(name);
if (raw == null) return defaultValue;
String text = raw.trim().toLowerCase();
if (text.endsWith("ms")) return Duration.ofMillis(Long.parseLong(text.replace("ms", "")));
long amount = Long.parseLong(text.substring(0, text.length() - 1));
return switch (text.charAt(text.length() - 1)) {
case 's' -> Duration.ofSeconds(amount);
case 'm' -> Duration.ofMinutes(amount);
case 'h' -> Duration.ofHours(amount);
default -> throw new IllegalArgumentException(name + " needs a unit (ms, s, m, h), got '" + raw + "'");
};
}
public static void main(String[] args) {
int maxConnections = intValue("DB_MAX_CONNECTIONS", 10);
boolean cacheEnabled = boolValue("CACHE_ENABLED", false);
Duration requestTimeout = durationValue("REQUEST_TIMEOUT", Duration.ofSeconds(30));
System.out.println("maxConnections = " + maxConnections);
System.out.println("cacheEnabled = " + cacheEnabled);
System.out.println("requestTimeout = " + requestTimeout + " (" + requestTimeout.toMillis() + " ms)");
}
}
java TypedEnv.java
DB_MAX_CONNECTIONS=25 CACHE_ENABLED=yes REQUEST_TIMEOUT=1500ms java TypedEnv.java
DB_MAX_CONNECTIONS=ten java TypedEnv.java
maxConnections = 10
cacheEnabled = false
requestTimeout = PT30S (30000 ms)
maxConnections = 25
cacheEnabled = true
requestTimeout = PT1.5S (1500 ms)
Exception in thread "main" java.lang.IllegalArgumentException: DB_MAX_CONNECTIONS must be a whole number, got 'ten'
at TypedEnv.intValue(TypedEnv.java:11)
at TypedEnv.main(TypedEnv.java:41)
How it works:
Boolean.parseBoolean("yes")would quietly returnfalse. The customboolValueaccepts common spellings and rejects anything else, so a typo cannot silently turn a feature off.Durationprints in ISO-8601 form:PT30Sis 30 seconds,PT1.5Sis 1.5 seconds. UsetoMillis()ortoSeconds()when an API needs a number.- The error message names the variable and the bad value, which is exactly what the person fixing the server needs.
System Properties vs Environment Variables
System properties are key-value pairs inside the JVM. Some are set by Java itself, and you add your own with -D on the command line.
public class SysProps {
public static void main(String[] args) {
// properties set by the JVM itself
System.out.println("java.version = " + System.getProperty("java.version"));
System.out.println("os.name = " + System.getProperty("os.name"));
System.out.println("user.dir = " + System.getProperty("user.dir"));
// properties you pass with -D, with a default
String port = System.getProperty("app.port", "8080");
boolean debug = Boolean.getBoolean("app.debug"); // true only if set to "true"
System.out.println("app.port = " + port);
System.out.println("app.debug = " + debug);
}
}
java -Dapp.port=9095 -Dapp.debug=true SysProps.java
java.version = 21.0.12
os.name = Linux
user.dir = /home/asha/course-server
app.port = 9095
app.debug = true
| Environment variable | System property | |
|---|---|---|
| Set with | Shell, systemd, Docker, CI | java -Dkey=value or System.setProperty |
| Read with | System.getenv("APP_PORT") | System.getProperty("app.port") |
| Naming style | APP_PORT | app.port |
| Visible to | The process and its child processes | Only this JVM |
| Changeable at runtime | No | Yes (System.setProperty) |
| Best for | Deployment settings, secrets, containers | JVM and library settings, quick overrides |
How it works:
-Doptions must come before-jaror the class name. Anything after them goes tomain(String[] args)instead.Boolean.getBoolean("app.debug")reads a system property namedapp.debug, not a string. The name is confusing, but it is handy for feature flags.- Containers and cloud platforms set environment variables, not
-Dflags, so apps that run in Docker usually read environment variables first.
Load Settings From a Properties File
When there are many settings, keep them in a .properties file. Package defaults inside the JAR and let a file on the server override them.
# src/main/resources/application.properties (inside the JAR)
app.name=Course Server
app.port=8080
db.url=jdbc:h2:mem:courses
db.pool.size=5
# /etc/course-server/application.properties (on the server)
db.url=jdbc:postgresql://db.internal:5432/courses
db.pool.size=20
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
public class PropsFile {
public static void main(String[] args) throws IOException {
Properties settings = new Properties();
// 1. defaults from the classpath (inside the JAR)
try (InputStream in = PropsFile.class.getResourceAsStream("/application.properties")) {
if (in == null) throw new IllegalStateException("application.properties not on classpath");
settings.load(in);
}
System.out.println("packaged: " + settings.getProperty("db.url") + ", pool=" + settings.getProperty("db.pool.size"));
// 2. optional file on the server overrides matching keys
Path external = Path.of(System.getProperty("app.config", "/etc/course-server/application.properties"));
if (Files.exists(external)) {
try (Reader reader = Files.newBufferedReader(external)) {
settings.load(reader); // later load() replaces existing keys
}
}
System.out.println("effective: " + settings.getProperty("db.url") + ", pool=" + settings.getProperty("db.pool.size"));
System.out.println("app.name: " + settings.getProperty("app.name"));
System.out.println("timeout: " + settings.getProperty("http.timeout", "30s"));
}
}
packaged: jdbc:h2:mem:courses, pool=5
effective: jdbc:postgresql://db.internal:5432/courses, pool=20
app.name: Course Server
timeout: 30s
How it works:
getResourceAsStream("/application.properties")finds the file on the classpath, which in a packaged app means inside the JAR (src/main/resourcesis copied there by Maven and Gradle).- Calling
load()a second time adds and replaces keys.app.namesurvives from the first file;db.urlanddb.pool.sizeare overridden. getProperty(key, default)returns the default when no file defines the key.-Dapp.config=/path/file.propertieslets each server point at its own file without rebuilding the JAR.
Per-Environment Profiles
A profile is a set of settings for one environment, such as dev, test or prod. A common pattern is one base file plus one file per profile, chosen by APP_ENV.
src/main/resources/
├── application.properties <- shared defaults
├── application-dev.properties <- only what differs in dev
└── application-prod.properties <- only what differs in prod
# application-prod.properties
db.url=jdbc:postgresql://db.internal:5432/courses
db.user=course_app
db.pool.size=20
cache.enabled=true
String profile = System.getenv().getOrDefault("APP_ENV", "dev");
Properties settings = new Properties();
loadClasspath(settings, "/application.properties"); // base
loadClasspath(settings, "/application-" + profile + ".properties"); // profile overrides
How it works:
- The profile file contains only the differences, so shared values live in one place.
- A missing profile file is simply skipped, so a new environment works with the base defaults until you add its file.
- This is the same idea Spring Boot uses with
spring.profiles.active, explained in the Spring Boot tutorial. The real-world example below implements it in plain Java.
Keep Secrets Out of Code and Logs
Passwords and API keys must never be in source code, in the JAR or in log output.
| Approach | How the secret arrives | Notes |
|---|---|---|
| Environment variable | DB_PASSWORD=... | Simple; visible to anyone who can inspect the process |
| Secret file | DB_PASSWORD_FILE=/run/secrets/db_password | Used by Docker and Kubernetes secrets; file mode 400 |
| Secrets manager | AWS Secrets Manager, Vault, Azure Key Vault | Fetched at startup with the provider's SDK |
// read DB_PASSWORD_FILE if set, otherwise DB_PASSWORD
static String secret(String name) throws IOException {
String fileName = System.getenv(name + "_FILE");
if (fileName != null) {
return Files.readString(Path.of(fileName)).strip(); // strip() removes the trailing newline
}
return System.getenv().getOrDefault(name, "");
}
String dbPassword = secret("DB_PASSWORD");
System.out.println("db.password = " + (dbPassword.isEmpty() ? "(empty)" : "****"));
db.password = ****
How it works:
- The
_FILEconvention keeps the secret out of the environment entirely. Tools likedocker inspectandps eshow environment variables, but not the contents of a file. strip()matters: files created withechoend with a newline, and a password with a hidden\nfails to log in.- Print a mask such as
****when logging configuration. Real values belong only in memory.
Note: Add your local
.envand secret files to.gitignoreso they are never committed. If a secret does reach Git history, change the secret; deleting the file later does not remove it from history.
Configuration Precedence
When the same setting can come from many places, define a clear order. The usual rule is "closest to the run wins":
| Priority | Source | Example |
|---|---|---|
| 1 (highest) | System property | -Ddb.pool.size=40 |
| 2 | Environment variable | DB_POOL_SIZE=30 |
| 3 | External file on the server | /etc/course-server/application.properties |
| 4 | Profile file in the JAR | application-prod.properties |
| 5 (lowest) | Base file in the JAR | application.properties |
How it works:
- Defaults live in the JAR, environment-specific values on the server, and one-off overrides on the command line.
- A naming rule connects the styles: the property
db.pool.sizemaps to the variableDB_POOL_SIZE(upper case, dots become underscores).
Real-World Example: A Typed AppConfig With Layered Java Environment Variables
This AppConfig record loads all sources in the order above, converts values to the right types, reads the password from a secret file, collects every problem before failing, and prints a summary with the password masked.
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/** Typed, validated application settings. Build it once at startup with AppConfig.load(). */
public record AppConfig(String environment, int port, String dbUrl, String dbUser,
String dbPassword, int dbPoolSize, Duration requestTimeout,
boolean cacheEnabled) {
public static AppConfig load() {
String environment = System.getenv().getOrDefault("APP_ENV", "dev");
Properties merged = new Properties();
// lowest to highest priority; each layer overrides the one before
loadClasspath(merged, "/application.properties");
loadClasspath(merged, "/application-" + environment + ".properties");
loadFile(merged, Path.of(System.getProperty("app.config", "/etc/course-server/application.properties")));
Source source = new Source(merged, System.getenv());
List<String> errors = new ArrayList<>();
AppConfig config = new AppConfig(
environment,
source.intValue("app.port", errors),
source.text("db.url", errors),
source.text("db.user", errors),
source.secret("db.password", errors),
source.intValue("db.pool.size", errors),
source.duration("request.timeout", errors),
Boolean.parseBoolean(source.raw("cache.enabled")));
if (!errors.isEmpty()) {
throw new IllegalStateException("Invalid configuration:\n - " + String.join("\n - ", errors));
}
return config;
}
/** Safe to log: the password is masked. */
public String summary() {
return """
environment = %s
port = %d
db.url = %s
db.user = %s
db.password = %s
db.pool.size = %d
request.timeout = %s
cache.enabled = %s""".formatted(environment, port, dbUrl, dbUser,
dbPassword.isEmpty() ? "(empty)" : "****", dbPoolSize, requestTimeout, cacheEnabled);
}
// ---------- loading helpers ----------
private static void loadClasspath(Properties target, String resource) {
try (InputStream in = AppConfig.class.getResourceAsStream(resource)) {
if (in != null) target.load(in);
} catch (IOException e) {
throw new IllegalStateException("Cannot read " + resource, e);
}
}
private static void loadFile(Properties target, Path file) {
if (!Files.exists(file)) return;
try (Reader reader = Files.newBufferedReader(file)) {
target.load(reader);
} catch (IOException e) {
throw new IllegalStateException("Cannot read " + file, e);
}
}
/** Looks up a key in: system property > environment variable > merged files. */
private record Source(Properties files, Map<String, String> env) {
static String envName(String key) { // db.pool.size -> DB_POOL_SIZE
return key.toUpperCase().replace('.', '_').replace('-', '_');
}
String raw(String key) {
String fromProperty = System.getProperty(key);
if (fromProperty != null) return fromProperty;
String fromEnv = env.get(envName(key));
if (fromEnv != null) return fromEnv;
return files.getProperty(key);
}
String text(String key, List<String> errors) {
String value = raw(key);
if (value == null || value.isBlank()) {
errors.add(key + " is required (set " + envName(key) + ")");
return "";
}
return value.trim();
}
int intValue(String key, List<String> errors) {
String value = text(key, errors);
if (value.isEmpty()) return 0;
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
errors.add(key + " must be a number, got '" + value + "'");
return 0;
}
}
Duration duration(String key, List<String> errors) {
String value = text(key, errors).toLowerCase();
try {
if (value.endsWith("ms")) return Duration.ofMillis(Long.parseLong(value.replace("ms", "")));
long amount = Long.parseLong(value.substring(0, value.length() - 1));
return switch (value.charAt(value.length() - 1)) {
case 's' -> Duration.ofSeconds(amount);
case 'm' -> Duration.ofMinutes(amount);
default -> throw new NumberFormatException();
};
} catch (RuntimeException e) {
errors.add(key + " must look like 500ms, 30s or 5m, got '" + value + "'");
return Duration.ZERO;
}
}
/** Secrets: env var, or a file named by <NAME>_FILE (Docker/Kubernetes secrets). */
String secret(String key, List<String> errors) {
String fileName = env.get(envName(key) + "_FILE");
if (fileName != null) {
try {
return Files.readString(Path.of(fileName)).strip();
} catch (IOException e) {
errors.add(key + ": cannot read secret file " + fileName);
return "";
}
}
String value = env.get(envName(key));
return value == null ? "" : value;
}
}
}
public class Main {
public static void main(String[] args) {
try {
AppConfig config = AppConfig.load();
System.out.println("Configuration loaded:");
System.out.println(config.summary());
// ... start the server with config.port(), config.dbUrl() ...
} catch (IllegalStateException e) {
System.err.println(e.getMessage());
System.exit(1); // fail fast: never start with a broken config
}
}
}
Resource and server files:
# src/main/resources/application.properties
app.port=8080
db.url=jdbc:h2:mem:courses
db.user=sa
db.pool.size=5
request.timeout=30s
cache.enabled=false
# /etc/course-server/application.properties
db.pool.size=30
Run 1 — a developer's laptop (no profile file for dev, no server file):
java -jar course-server.jar
Configuration loaded:
environment = dev
port = 8080
db.url = jdbc:h2:mem:courses
db.user = sa
db.password = (empty)
db.pool.size = 5
request.timeout = PT30S
cache.enabled = false
Run 2 — production (profile file, server file, secret file and one environment override):
APP_ENV=prod DB_PASSWORD_FILE=/run/secrets/db_password REQUEST_TIMEOUT=45s java -jar course-server.jar
Configuration loaded:
environment = prod
port = 8080
db.url = jdbc:postgresql://db.internal:5432/courses
db.user = course_app
db.password = ****
db.pool.size = 30
request.timeout = PT45S
cache.enabled = true
Run 3 — a broken setup:
APP_ENV=prod APP_PORT=eighty REQUEST_TIMEOUT=10x java -Ddb.url= -jar course-server.jar; echo "exit=$?"
Invalid configuration:
- app.port must be a number, got 'eighty'
- db.url is required (set DB_URL)
- request.timeout must look like 500ms, 30s or 5m, got '10x'
exit=1
How it works:
- Layered loading. The base file, the
prodprofile and the server file are merged into onePropertiesobject, each overriding the one before. That is whydb.pool.sizeis 5 in the JAR, 20 in the profile and finally 30 from/etc/course-server. - Overrides on top.
Source.raw()checks system properties, then environment variables (REQUEST_TIMEOUT), then the merged files. In Run 2 the variable wins over the30sfrom the file. - Typed and immutable. The rest of the app gets an
AppConfigrecord with anint, aDurationand aboolean, never raw strings, and the record cannot be changed after startup. - All errors at once. Problems are collected in a list, so Run 3 reports all three mistakes in one go instead of one per restart.
-Ddb.url=sets an empty system property, which wins over the profile file and triggers the "required" check. - Safe output.
summary()masks the password, so the startup log can show the effective configuration without leaking secrets. The same JAR now runs unchanged under systemd, in Docker (env_file, secrets) or on a laptop. The next lesson, Java Logging, replaces theseSystem.outlines with proper log messages.