Java environment config loader with defaults
Java
import java.util.Map;
public final class EnvConfig {
public record Config(String host, int port, boolean debug) {}
public static Config load(Map<String, String> env) {
String host = env.getOrDefault("APP_HOST", "localhost");
if (host.isBlank()) throw new IllegalStateException("APP_HOST must not be blank");
int port;
try {
port = Integer.parseInt(env.getOrDefault("APP_PORT", "8080"));
} catch (NumberFormatException e) {
throw new IllegalStateException("APP_PORT must be an integer", e);
}
if (port < 1 || port > 65535) throw new IllegalStateException("APP_PORT out of range: " + port);
return new Config(host, port, Boolean.parseBoolean(env.getOrDefault("APP_DEBUG", "false")));
}
}