Loading configuration from a properties file
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A password typed into the code or committed to GitHub is leaked for good, and every new computer needs its own URL and pool size. The settings must live outside the code.
application.properties on the classpath
A properties file is a text file of key=value lines that java.util.Properties reads into a map of strings. application.properties sits in src/main/resources and is loaded from the classpath.
Example 1 is the file itself. Example 2 loads it from the classpath and prints every setting.
Example 1 · src/main/resources/application.properties
Runs in: the shoplite-console Maven project
cat src/main/resources/application.properties# ShopLite settings for this computer. Not committed: copy application.properties.example db.url=jdbc:mysql://localhost:3306/shoplite db.user=shoplite_app # The password comes from the DB_PASSWORD environment variable db.password= db.pool.max-size=10 db.pool.connection-timeout-ms=5000 db.init=false
What this code does
#starts a comment line. Every other line iskey=value; spaces around=are allowed, but spaces at the end of a value are kept as part of it.- Keys use dots to group settings (
db.pool.*). The password line is empty on purpose: it will come from an environment variable. catprints a file in macOS Terminal and in Windows PowerShell alike.
Example 2 · Loading application.properties from the classpath
Runs in: the shoplite-console Maven project
import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets;import java.util.Map;import java.util.Properties;import java.util.TreeMap;
public class ClasspathConfigDemo { static Properties loadFromClasspath(String name) throws IOException { try (InputStream in = ClasspathConfigDemo.class.getClassLoader().getResourceAsStream(name)) { if (in == null) { throw new IllegalStateException(name + " was not found on the classpath. Copy " + "application.properties.example to src/main/resources/application.properties"); } Properties props = new Properties(); props.load(new InputStreamReader(in, StandardCharsets.UTF_8)); return props; } }
public static void main(String[] args) throws IOException { Properties props = loadFromClasspath("application.properties"); System.out.println("Loaded " + props.size() + " settings:"); for (Map.Entry<Object, Object> e : new TreeMap<>(props).entrySet()) { System.out.println(" " + e.getKey() + " = '" + e.getValue() + "'"); } System.out.println("db.init as a boolean: " + Boolean.parseBoolean(props.getProperty("db.init"))); System.out.println("Missing key: " + props.getProperty("db.schema")); System.out.println("Missing key with default: " + props.getProperty("db.schema", "shoplite"));
try { loadFromClasspath("aplication.properties"); // a one-letter typo } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } }}Loaded 6 settings: db.init = 'false' db.password = '' db.pool.connection-timeout-ms = '5000' db.pool.max-size = '10' db.url = 'jdbc:mysql://localhost:3306/shoplite' db.user = 'shoplite_app' db.init as a boolean: false Missing key: null Missing key with default: shoplite Error: aplication.properties was not found on the classpath. Copy application.properties.example to src/main/resources/application.properties
What this code does
getResourceAsStreamfinds the file intarget/classes, where Maven copied it fromsrc/main/resources. The same code works from the IDE, frommvn exec:javaand from a JAR.- Every value is a
String, and a missing key givesnullunless you pass a default. A missing file also givesnull, not an exception, so the code checks it and explains what to do. new InputStreamReader(in, StandardCharsets.UTF_8)reads the file as UTF-8. The plainload(InputStream)reads ISO-8859-1 and would garble characters such as ₹ or Hindi text.
Maven copies src/main/resources into target/classes, which is on the classpath: the folders and JARs Java loads classes and files from. Keep the settings that change between computers here instead of in code: the database URL, the user, pool sizes, timeouts, feature switches. Changing the pool size should mean editing one line in a file, not recompiling.
Watch three traps. getResourceAsStream returns null (no exception) when the file is missing. Every value is a String, so you must convert numbers yourself. And load(InputStream) assumes ISO-8859-1; wrap the stream in a UTF-8 reader.
Predict the output
Predict what Properties returns
The file has these lines. Which value does each call return?
Round 1 of 2
Environment variables override file values
An environment variable is a named value set outside the program, in the terminal, the IDE run settings or the server, and read with System.getenv("NAME"). Real apps check the environment first, then the file, then a default in code.
Example 3 looks each setting up in the environment first and in the file second, and prints where every value came from.
Example 3 · Environment variables override the file
import java.io.IOException;import java.io.StringReader;import java.util.Locale;import java.util.Map;import java.util.Properties;
// Looks a setting up in the environment first, then in the properties fileclass Settings { private final Properties file; private final Map<String, String> env;
Settings(Properties file, Map<String, String> env) { this.file = file; this.env = env; }
// db.pool.max-size -> DB_POOL_MAX_SIZE static String envName(String key) { return key.toUpperCase(Locale.ROOT).replace('.', '_').replace('-', '_'); }
String get(String key) { String fromEnv = env.get(envName(key)); if (fromEnv != null && !fromEnv.isBlank()) { return fromEnv.trim(); } String fromFile = file.getProperty(key); return fromFile == null || fromFile.isBlank() ? null : fromFile.trim(); }
String source(String key) { String fromEnv = env.get(envName(key)); if (fromEnv != null && !fromEnv.isBlank()) { return "environment variable " + envName(key); } return file.getProperty(key) != null ? "application.properties" : "not set"; }}
public class EnvOverrideDemo { public static void main(String[] args) throws IOException { Properties file = new Properties(); file.load(new StringReader(""" db.url=jdbc:mysql://localhost:3306/shoplite db.user=shoplite_app db.password= db.pool.max-size=10 """));
Map<String, String> env = Map.of( "DB_PASSWORD", "Fest@2026", "DB_POOL_MAX_SIZE", "4");
Settings settings = new Settings(file, env); for (String key : new String[] {"db.url", "db.user", "db.password", "db.pool.max-size", "db.init"}) { String value = settings.get(key); String shown = key.equals("db.password") && value != null ? "****" : value; System.out.printf("%-17s = %-40s (%s)%n", key, shown, settings.source(key)); } }}db.url = jdbc:mysql://localhost:3306/shoplite (application.properties) db.user = shoplite_app (application.properties) db.password = **** (environment variable DB_PASSWORD) db.pool.max-size = 4 (environment variable DB_POOL_MAX_SIZE) db.init = null (not set)
What this code does
envNameturns a key into its environment variable name: upper case, with dots and dashes changed to underscores.getchecks the environment first and the file second, soDB_POOL_MAX_SIZE=4beats the file's10. The password exists only in the environment, so it never sits in a file.- The environment is passed in as a
Map. The real app passesSystem.getenv(); this example passes a fixed map so its output is always the same.
Reading the environment first keeps secrets out of files: the password lives only in the environment of the machine that needs it. It also lets one build run on your laptop, a college lab PC and a cloud server, each with its own values, without editing any file.
Use one naming rule so nobody guesses: upper case, with dots and dashes turned into underscores, so db.pool.max-size becomes DB_POOL_MAX_SIZE. Spring Boot uses the same rule, as Section 15 shows. To set a variable for one terminal window, use $env:DB_PASSWORD = "your-password" in PowerShell or export DB_PASSWORD='your-password' in macOS Terminal, then run the app from that window; in IntelliJ IDEA, fill in Run, Edit Configurations, Environment variables. Avoid setx for passwords: it saves them permanently.
Order of execution
Order the lookup
Tap the places Settings checks for db.pool.max-size, from first to last.
An immutable AppConfig record built once at startup
AppConfig is one immutable record that holds every setting the app needs, already converted to the right types. main builds it once at startup and passes it to whoever needs it.
Example 4 builds an AppConfig from a file and an environment, then prints it with the password hidden.
Example 4 · An immutable AppConfig record
import java.io.IOException;import java.io.StringReader;import java.util.Locale;import java.util.Map;import java.util.Properties;
// Immutable: every field is final, there are no setters, and it is built once at startuprecord AppConfig(String dbUrl, String dbUser, String dbPassword, int poolMaxSize, boolean dbInit) {
static AppConfig from(Properties file, Map<String, String> env) { return new AppConfig( value("db.url", file, env, null), value("db.user", file, env, null), value("db.password", file, env, ""), Integer.parseInt(value("db.pool.max-size", file, env, "10")), Boolean.parseBoolean(value("db.init", file, env, "false"))); }
private static String value(String key, Properties file, Map<String, String> env, String fallback) { String envName = key.toUpperCase(Locale.ROOT).replace('.', '_').replace('-', '_'); String v = env.get(envName); if (v == null || v.isBlank()) { v = file.getProperty(key); } return v == null || v.isBlank() ? fallback : v.trim(); }
@Override public String toString() { // never print the password, not even in logs return "AppConfig[dbUrl=" + dbUrl + ", dbUser=" + dbUser + ", dbPassword=****" + ", poolMaxSize=" + poolMaxSize + ", dbInit=" + dbInit + "]"; }}
public class AppConfigDemo { public static void main(String[] args) throws IOException { Properties file = new Properties(); file.load(new StringReader(""" db.url=jdbc:mysql://localhost:3306/shoplite db.user=shoplite_app db.pool.max-size=5 """)); Map<String, String> env = Map.of("DB_PASSWORD", "Fest@2026");
AppConfig config = AppConfig.from(file, env); System.out.println(config); System.out.println("Pool size: " + config.poolMaxSize()); System.out.println("Run scripts at startup: " + config.dbInit()); }}AppConfig[dbUrl=jdbc:mysql://localhost:3306/shoplite, dbUser=shoplite_app, dbPassword=****, poolMaxSize=5, dbInit=false] Pool size: 5 Run scripts at startup: false
What this code does
- A record's fields are final and it has no setters, so once
AppConfig.fromreturns, no code can change a setting by accident halfway through a run. - Numbers and booleans are converted once, here. The rest of the app reads
config.poolMaxSize()as anintand never parses strings again. - The overridden
toString()prints****instead of the password, so logging the config is safe. The record's defaulttoString()would print the password.
Without it, System.getenv and getProperty calls end up spread across many classes. Nobody can see which settings exist, the same number is parsed in three places, and a typo in one key name fails only when that screen is opened.
Make the builder take the file contents and the environment as parameters: AppConfig.from(Properties, Map<String, String>). The app passes the real ones; a test passes small fixed ones. Override toString() so the password never reaches a log.
Find the bug
Find the wrong line
Each snippet misuses AppConfig. Find the line that is wrong.
The pool size is needed when the pool is created.
Round 1 of 2Validating required values and number formats with clear errors
Fail fast means checking every setting at startup and stopping the app at once with a clear message when one is wrong, instead of failing later in a confusing way.
Example 5 collects every problem in a settings file and reports them together, each one naming the key and the variable that fixes it.
Example 5 · Validating every setting and reporting all problems
import java.io.IOException;import java.io.StringReader;import java.util.ArrayList;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Properties;
class StartupException extends RuntimeException { StartupException(String message) { super(message); }}
class SettingsReader { private final Properties file; private final Map<String, String> env; private final List<String> errors = new ArrayList<>();
SettingsReader(Properties file, Map<String, String> env) { this.file = file; this.env = env; }
static String envName(String key) { return key.toUpperCase(Locale.ROOT).replace('.', '_').replace('-', '_'); }
private String raw(String key) { String v = env.get(envName(key)); if (v == null || v.isBlank()) { v = file.getProperty(key); } return v == null || v.isBlank() ? null : v.trim(); }
String required(String key) { String v = raw(key); if (v == null) { errors.add("missing " + key + " (set " + envName(key) + " or " + key + " in application.properties)"); } return v; }
String optional(String key, String fallback) { String v = raw(key); return v == null ? fallback : v; }
int intValue(String key, int fallback, int min, int max) { String v = raw(key); if (v == null) { return fallback; } try { int n = Integer.parseInt(v); if (n < min || n > max) { errors.add(key + " must be between " + min + " and " + max + ", got " + n); } return n; } catch (NumberFormatException e) { errors.add(key + " must be a whole number, got '" + v + "'"); return fallback; } }
boolean boolValue(String key, boolean fallback) { String v = raw(key); if (v == null) { return fallback; } if (!v.equalsIgnoreCase("true") && !v.equalsIgnoreCase("false")) { errors.add(key + " must be true or false, got '" + v + "'"); return fallback; } return Boolean.parseBoolean(v); }
void throwIfErrors() { if (!errors.isEmpty()) { throw new StartupException("Invalid configuration:\n - " + String.join("\n - ", errors)); } }}
record AppConfig(String dbUrl, String dbUser, String dbPassword, int poolMaxSize, boolean dbInit) { static AppConfig from(Properties file, Map<String, String> env) { SettingsReader s = new SettingsReader(file, env); String url = s.required("db.url"); String user = s.required("db.user"); String password = s.optional("db.password", ""); int poolMaxSize = s.intValue("db.pool.max-size", 10, 1, 50); boolean dbInit = s.boolValue("db.init", false); s.throwIfErrors(); return new AppConfig(url, user, password, poolMaxSize, dbInit); }}
public class ConfigValidationDemo { static void tryLoad(String title, String fileText, Map<String, String> env) throws IOException { Properties file = new Properties(); file.load(new StringReader(fileText)); System.out.println(title); try { AppConfig c = AppConfig.from(file, env); System.out.println(" OK: pool " + c.poolMaxSize() + ", init " + c.dbInit()); } catch (StartupException e) { System.out.println(" " + e.getMessage().replace("\n", "\n ")); } }
public static void main(String[] args) throws IOException { tryLoad("Good file:", """ db.url=jdbc:mysql://localhost:3306/shoplite db.user=shoplite_app db.pool.max-size=8 db.init=true """, Map.of());
tryLoad("Typos and a missing value:", """ db.url=jdbc:mysql://localhost:3306/shoplite db.pool.max-size=ten db.init=yes """, Map.of());
tryLoad("Fixed by environment variables:", """ db.url=jdbc:mysql://localhost:3306/shoplite db.pool.max-size=ten """, Map.of("DB_USER", "shoplite_app", "DB_POOL_MAX_SIZE", "6")); }}Good file:
OK: pool 8, init true
Typos and a missing value:
Invalid configuration:
- missing db.user (set DB_USER or db.user in application.properties)
- db.pool.max-size must be a whole number, got 'ten'
- db.init must be true or false, got 'yes'
Fixed by environment variables:
OK: pool 6, init falseWhat this code does
SettingsReaderrecords each problem instead of throwing at the first one, so a learner who copied a bad file fixes everything in one go.db.init=yeswould silently becomefalsewithBoolean.parseBoolean.boolValueaccepts onlytrueorfalseand reports anything else.- The third case shows the override rule at work: the environment supplies the missing user and replaces the bad pool size, so the file can stay as it is.
A message such as NumberFormatException: For input string: "ten" makes the user hunt; db.pool.max-size must be a whole number, got 'ten' does not.
Be strict with booleans. Boolean.parseBoolean("yes") returns false with no error, so a learner who writes db.init=yes would wonder why the scripts never run.
Predict the output
Predict the boolean
The file says db.init=yes. What does the app read?
Committing application.properties.example, ignoring the real file
An example file, application.properties.example, is a committed copy of the settings with every key, safe sample values and comments. The real application.properties is listed in .gitignore, so secrets never reach Git.
Example 6 copies the example file to the real name, then asks Git which line of .gitignore hides it.
Example 6 · Ignore the real file, commit the example
Runs in: the shoplite-console project folder with Git
cp src/main/resources/application.properties.example src/main/resources/application.propertiesgit status --short -uallgit check-ignore -v src/main/resources/application.properties?? .gitignore ?? pom.xml ?? src/main/resources/application.properties.example .gitignore:6:src/main/resources/application.properties src/main/resources/application.properties
What this code does
git statuslists the example file but notapplication.properties: Git does not even see the real file, so it cannot be committed by accident.git check-ignore -vtells you which line of.gitignorehides a file (line 6 here). Use it whenever you are unsure whether a secret file is safe.
The real file may hold machine-specific values, and someone will one day type a password into it. If it is ignored, that password cannot end up on GitHub, where it would stay in the history even after you delete the line.
In ShopLite the file is also optional: when it is missing, every value can come from environment variables, which is how servers usually run. The routine for the team:
.gitignoregets the linesrc/main/resources/application.properties.- The example file is committed and kept up to date whenever a key is added.
- Secrets stay empty in both files and come from environment variables.
- The README says: copy the example, then set
DB_PASSWORD.
Fix the error
Fix the .gitignore
Read what Git shows, then pick the line that fixes the file.
The real settings file appears in git status and could be committed.
Error
?? src/main/resources/application.properties (the real file is untracked, not ignored)
Next step
Check your understanding
12 quick questions