java 55 lines · 6 steps

Loading typed config from env vars in Java

A Java record reads environment variables into an immutable, type-safe configuration object with defaults and validation.

Explained by highlit
1public record AppConfig(
2 String host,
3 int port,
4 String databaseUrl,
5 int maxConnections,
6 Duration requestTimeout,
7 boolean debugEnabled) {
8 
9 public static AppConfig fromEnvironment() {
10 return new AppConfig(
11 get("APP_HOST", "0.0.0.0"),
12 getInt("APP_PORT", 8080),
13 require("DATABASE_URL"),
14 getInt("DB_MAX_CONNECTIONS", 10),
15 Duration.ofSeconds(getInt("REQUEST_TIMEOUT_SECONDS", 30)),
16 getBool("DEBUG", false));
17 }
18 
19 private static String get(String key, String fallback) {
20 String value = System.getenv(key);
21 return (value == null || value.isBlank()) ? fallback : value.trim();
22 }
23 
24 private static String require(String key) {
25 String value = System.getenv(key);
26 if (value == null || value.isBlank()) {
27 throw new IllegalStateException("Missing required environment variable: " + key);
28 }
29 return value.trim();
30 }
31 
32 private static int getInt(String key, int fallback) {
33 String value = System.getenv(key);
34 if (value == null || value.isBlank()) {
35 return fallback;
36 }
37 try {
38 return Integer.parseInt(value.trim());
39 } catch (NumberFormatException e) {
40 throw new IllegalStateException("Invalid integer for " + key + ": " + value, e);
41 }
42 }
43 
44 private static boolean getBool(String key, boolean fallback) {
45 String value = System.getenv(key);
46 if (value == null || value.isBlank()) {
47 return fallback;
48 }
49 return switch (value.trim().toLowerCase()) {
50 case "true", "1", "yes", "on" -> true;
51 case "false", "0", "no", "off" -> false;
52 default -> throw new IllegalStateException("Invalid boolean for " + key + ": " + value);
53 };
54 }
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Records give you an immutable, self-documenting config object with no boilerplate constructor or getters.
  2. 2Centralizing env-var parsing in typed helpers keeps defaults, coercion, and validation consistent across every field.
  3. 3Failing fast with a clear exception on missing or malformed values surfaces misconfiguration at startup instead of runtime.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Loading typed config from env vars in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code