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
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
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.