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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Records give you an immutable, self-documenting config object with no boilerplate constructor or getters.
- 2Centralizing env-var parsing in typed helpers keeps defaults, coercion, and validation consistent across every field.
- 3Failing fast with a clear exception on missing or malformed values surfaces misconfiguration at startup instead of runtime.
Related explainers
php
<?php namespace App\Validation;
Building a reusable address form validator in PHP
validation
error-accumulation
regex
Intermediate
9 steps
java
public class RequestThrottler { private final Semaphore permits; private final long acquireTimeoutMillis;
Bounding concurrency with a Semaphore in Java
concurrency
semaphore
rate-limiting
Intermediate
6 steps
php
<?php namespace App\Http\Controllers;
A cached autocomplete endpoint in Laravel
caching
validation
query-ranking
Intermediate
8 steps
java
public List<DailySample> backfillMissingDates(List<DailySample> samples, double fillValue) { if (samples.isEmpty()) { return List.of(); }
Backfilling gaps in a daily time series in Java
streams
time-series
treemap
Intermediate
5 steps
java
public final class Ulid { private static final char[] ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ".toCharArray(); private static final SecureRandom RANDOM = new SecureRandom();
How to generate a ULID in Java
base32-encoding
bit-manipulation
identifiers
Intermediate
8 steps
java
@RestController @RequestMapping("/api/reports") public class ReportController {
Header-driven endpoints in a Spring controller
rest api
request headers
dependency injection
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/loading-typed-config-from-env-vars-in-java-explained-java-88b0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.