Environment variables and secrets
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's database password must reach the app on every computer, yet it must never appear in Java code or in Git. Anyone who can read the repository would otherwise own the database.
${DB_PASSWORD} placeholders and SPRING_DATASOURCE_* names
A secret is a value that gives access to something, such as a database password, an API key or a token. Secrets never go into Java code or into Git.
spring.datasource.password=${DB_PASSWORD} points the setting at the variable DB_PASSWORD. The committed file then holds only the name of the secret, never its value.
Example 1 · application.properties with placeholders, and DatabaseCheck.java
Runs in: the config-lab practice project with spring-boot-starter-jdbc, mysql-connector-j and the ShopLite database
# src/main/resources/application.propertiesspring.main.banner-mode=offlogging.level.root=warn
spring.datasource.url=${DB_URL:jdbc:mysql://localhost:3306/shoplite}spring.datasource.username=${DB_USER}spring.datasource.password=${DB_PASSWORD}
// src/main/java/com/shoplite/lab/DatabaseCheck.javapackage com.shoplite.lab;
import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class DatabaseCheck implements CommandLineRunner {
private final DataSource dataSource;
public DatabaseCheck(DataSource dataSource) { // Spring Boot built it from spring.datasource.* this.dataSource = dataSource; }
@Override public void run(String... args) throws SQLException { try (Connection con = dataSource.getConnection(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM products")) { DatabaseMetaData meta = con.getMetaData(); rs.next(); System.out.println("Connected to " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion()); System.out.println("Products in the catalog: " + rs.getInt(1)); } }}$ DB_USER=shoplite_app DB_PASSWORD='...' java -jar target/config-lab-0.0.1-SNAPSHOT.jar Connected to MySQL 9.4.0 Products in the catalog: 15
What this code does
- The file names
DB_URL,DB_USERandDB_PASSWORDbut holds no secret value, so it can be committed.DB_URLfalls back to the local database when it is not set. DatabaseCheckreceives theDataSourceBoot built from those settings and runs one query; 15 is the number of products in the ShopLite seed data. Your MySQL version will differ.- Running with
SPRING_DATASOURCE_PASSWORDinstead ofDB_PASSWORDalso works: that variable sets the same setting directly.
${DB_URL:jdbc:mysql://localhost:3306/shoplite} adds a safe default for a value that is not secret. You can also skip the line completely: by relaxed binding, the variable SPRING_DATASOURCE_PASSWORD sets spring.datasource.password directly. Short names like DB_PASSWORD are easier to type and to share between apps; the long names need no line in the file at all.
The examples add spring-boot-starter-jdbc and mysql-connector-j to config-lab. Boot then builds a DataSource (a pool of database connections) from the spring.datasource.* settings, and DatabaseCheck borrows one connection to count products.
shoplite_app you created for the JDBC section, never root. The last module of this section builds the real ShopLite repositories on this DataSource.Setting environment variables on your computer
An environment variable is a name and value that the operating system hands to every program started from that terminal or tool.
Set the variables in the terminal or IDE that starts the app. Example 2 sets two of them and then runs the jar.
Example 2 · Set variables, then run the app
Runs in: the config-lab practice project with spring-boot-starter-jdbc, mysql-connector-j and the ShopLite database
export DB_USER=shoplite_appexport DB_PASSWORD='your-password-here'java -jar target/config-lab-0.0.1-SNAPSHOT.jarConnected to MySQL 9.4.0 Products in the catalog: 15
What this code does
exportmakes the variable visible to programs started from this window, herejava. Single quotes keep characters such as#,$and!as they are. Type the real password where the example saysyour-password-here.- In Windows PowerShell the same two lines are
$env:DB_USER = 'shoplite_app'and$env:DB_PASSWORD = 'your-password-here', andRemove-Item Env:DB_USER, Env:DB_PASSWORDremoves them again. - The password stays in your shell history. On a shared computer, put it in
config/application.properties(next section) instead.
A variable set in one terminal window is not seen by another window, and it disappears when the window closes, which is often what you want for a password. After changing a variable, restart the app: a running Java process never sees new values. To keep a variable for every new window, use Start → "Edit environment variables for your account" on Windows, or an export line in ~/.zshrc on macOS (a file that now holds a secret, so never copy it into a project).
In IntelliJ IDEA, open Run → Edit Configurations, select the app's configuration and fill the Environment variables field: DB_USER=shoplite_app;DB_PASSWORD=.... IntelliJ keeps it in .idea/workspace.xml, and the .idea folder is in the .gitignore that Spring Initializr creates. In VS Code, add an "env": { "DB_PASSWORD": "..." } block to .vscode/launch.json, and keep .vscode/ in .gitignore.
Never commit secrets: .gitignore and an example file
.gitignore is the file that lists the paths Git never tracks. git check-ignore -v <file> shows whether a file is ignored and which line says so.
Put your real values in config/application.properties, list that file in .gitignore, and commit only an application.properties.example with placeholder values.
Example 3 · .gitignore, the example file and your local copy
Runs in: the config-lab practice project with spring-boot-starter-jdbc, mysql-connector-j and the ShopLite database
# .gitignoretarget/.idea/*.iml.vscode/logs/# Local settings and secrets: never commitconfig/application.properties.env# config/application.properties.example (committed: no real values)# Copy this file to config/application.properties and fill in your values.# config/application.properties is in .gitignore, so it never reaches GitHub.DB_URL=jdbc:mysql://localhost:3306/shopliteDB_USER=shoplite_appDB_PASSWORD=change-me# config/application.properties (your copy: ignored by Git)DB_URL=jdbc:mysql://localhost:3306/shopliteDB_USER=shoplite_appDB_PASSWORD=your-real-password$ git status --short --untracked-files=all ?? .gitignore ?? config/application.properties.example ?? src/main/resources/application.properties $ git check-ignore -v config/application.properties .gitignore:8:config/application.properties config/application.properties $ java -jar target/config-lab-0.0.1-SNAPSHOT.jar Connected to MySQL 9.4.0 Products in the catalog: 15
What this code does
git statuslists the example file but notconfig/application.properties: Git does not even see it.git check-ignore -vshows that line 8 of.gitignoreis the reason.- The app is started from the project folder with no environment variables at all. Boot read
config/application.propertiesfrom that folder and resolved${DB_PASSWORD}from it. - On a server, nobody creates this file: the same keys come from real environment variables, which win over it.
Everything you push to GitHub stays in its history for ever, and public repositories are scanned by bots within minutes. So secrets never enter Git: not in application.properties, not in a test, not in a commit message. Spring Boot automatically reads config/application.properties from the folder you start the app in, and its values beat the ones inside the jar.
A new teammate copies the example file to config/application.properties, fills in their own password and runs the app. git check-ignore -v <file> proves a file is ignored and names the .gitignore line that does it.
Failing fast in prod when a secret is missing
Fail fast means stopping at start-up when a required setting is missing, instead of failing later in the first request that needs it.
A missing DB_PASSWORD does not stop the app by itself. A small @Profile("prod") bean that calls env.getRequiredProperty(key) makes a missing secret stop start-up.
Example 4 · RequiredSettingsCheck.java: start-up stops when DB_PASSWORD is missing
Runs in: the config-lab practice project with spring-boot-starter-jdbc, mysql-connector-j and the ShopLite database
// src/main/java/com/shoplite/lab/RequiredSettingsCheck.javapackage com.shoplite.lab;
import java.util.List;
import org.springframework.context.annotation.Profile;import org.springframework.core.env.Environment;import org.springframework.stereotype.Component;
@Component@Profile("prod")public class RequiredSettingsCheck {
private static final List<String> REQUIRED = List.of( "spring.datasource.url", "spring.datasource.username", "spring.datasource.password");
public RequiredSettingsCheck(Environment env) { for (String key : REQUIRED) { // Throws at startup when the key or a ${...} inside it has no value String value = env.getRequiredProperty(key); if (value.isBlank()) { throw new IllegalStateException("Setting " + key + " is empty"); } } }}$ DB_USER=shoplite_app java -jar target/config-lab-0.0.1-SNAPSHOT.jar (DB_PASSWORD not set, no profile)
2026-10-16T12:03:37.381+05:30 ERROR 4732 --- [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
Caused by: java.sql.SQLException: Access denied for user 'shoplite_app'@'localhost' (using password: YES)
... 22 common frames omitted
$ DB_USER=shoplite_app java -jar target/config-lab-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
2026-10-16T12:03:43.567+05:30 ERROR 30472 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requiredSettingsCheck' defined in URL [...]: Failed to instantiate [com.shoplite.lab.RequiredSettingsCheck]: Constructor threw exception
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.shoplite.lab.RequiredSettingsCheck]: Constructor threw exception
... 25 common frames omitted
Caused by: org.springframework.util.PlaceholderResolutionException: Could not resolve placeholder 'DB_PASSWORD' in value "${DB_PASSWORD}"
... 27 common frames omittedWhat this code does
- First run, no profile: the app starts with the literal password
${DB_PASSWORD}and fails only whenDatabaseCheckconnects. In a web app, that is the first request that touches the database. - Second run, prod:
RequiredSettingsCheckis created during start-up,getRequiredPropertycannot resolve${DB_PASSWORD}, and the app stops before it ever serves a request. The lastCaused bynames the missing variable. - The check is
@Profile("prod"), so a laptop without the variables can still run the parts that do not need a database.
Boot leaves an unresolved placeholder inside spring.datasource.* as the literal text ${DB_PASSWORD}, the app starts, and the first database call fails with Access denied ... (using password: YES). On a server, that first call can be a customer's order hours later. getRequiredProperty resolves placeholders strictly, so a missing variable throws Could not resolve placeholder 'DB_PASSWORD' and the app never starts.
Never give a secret a default such as ${DB_PASSWORD:admin123}. A default password is a password in Git, and it hides the missing variable instead of reporting it.
What to do if a secret was pushed to GitHub
To rotate a secret is to replace it with a new one at its source, for example a new database password, so the leaked value stops working.
Rotate first: treat a pushed secret as stolen and replace it at the source. Then stop tracking the file, as the commands below do.
# 1. Rotate first: give the database user a new password (run as the MySQL admin)ALTER USER 'shoplite_app'@'localhost' IDENTIFIED BY 'a-new-long-password';# 2. Stop tracking the file and make Git ignore it from now ongit rm --cached config/application.propertiesecho config/application.properties >> .gitignoregit commit -m "Stop tracking local secrets"Change the database password (or revoke the API key) and update the environment variables of every place that uses it. Deleting the file does not help, because the old commit still contains it.
To remove the secret from the history too, rewrite it with a tool such as git filter-repo and force-push, and tell everyone to clone again. Rotation is what actually protects you; cleaning history only reduces the noise. GitHub's secret scanning and push protection can warn about or block known kinds of keys before they are pushed; keep them turned on for your repositories.
Order of execution
Order the clean-up
A database password reached GitHub. Put the steps in the right order.
Next step
Check your understanding
11 quick questions