Sub topic 14
Keeping secrets out of your configuration files
This chapter assumes you know how property precedence works, how relaxed binding maps DB_PASSWORD-style names to properties, and how @ConfigurationProperties binds values. It builds on those to show where credentials should live instead of in application.yaml.
Why secrets don't belong in the repository
A secret is any value that grants access: a database password, an API key, a signing key, or a token. Anything committed to version control stays in the history even after you delete it. It is also copied to every clone, CI log, and backup.
The fix follows from externalized configuration. The jar contains the shape of the configuration and safe defaults. The environment supplies the secret at deploy time. Spring Boot gives you four ways to do that:
| Mechanism | Where the secret lives | Typical use |
|---|---|---|
| Placeholder plus environment variable | Process environment | Containers, CI, PaaS |
| `optional:file:` import | An untracked local file | Developer machines |
| `configtree:` import | A directory of files, one per value | Kubernetes and Docker secrets |
| External secret store import | A vault or cloud service | Shared, rotated secrets |
Placeholders that point to the environment
Commit the key but not the value. A ${...} placeholder is resolved against all property sources, including environment variables.
spring:
datasource:
url: jdbc:postgresql://localhost:5432/app
username: app
password: ${DB_PASSWORD}Then supply the value when you start the process:
DB_PASSWORD='s3cret-value' java -jar app.jarBecause there is no default after the name, a missing variable stops startup with an error such as Could not resolve placeholder 'DB_PASSWORD'. That is what you want in production. Avoid ${DB_PASSWORD:changeme}, because a forgotten variable would then start the application with a known password.
Relaxed binding also lets you skip the placeholder. If the file defines nothing for spring.datasource.password, the variable SPRING_DATASOURCE_PASSWORD sets it directly. A placeholder is still clearer, because the file documents which variable is expected.
Developer machines: an untracked override file
Developers need real values locally, but they shouldn't type them on every run. Import an optional file and keep it out of Git:
spring:
profiles:
group:
prod:
- proddb
- prodmq
config:
import: "optional:file:./local-overrides.yaml"The optional: prefix means startup continues if the file is missing. That keeps CI and production working, because the file exists only on laptops. Without the prefix, a missing file fails startup.
An imported document takes precedence over the document that imports it. A value in local-overrides.yaml therefore wins over the same key in application.yaml. Put the file in .gitignore:
local-overrides.yamlCommit a local-overrides.example.yaml with fake values so new teammates know which keys to fill in.
Mounted secrets: config trees
Kubernetes Secrets and Docker secrets arrive as files. Each file is named after a value, and its content is the value. Spring Boot can import such a directory as properties with configtree:.
Suppose the platform mounts these files:
/run/secrets/db.password
/run/secrets/app.mail.api-keyImport the whole directory:
spring:
config:
import: "optional:configtree:/run/secrets/"Each file name becomes a property name, so db.password and app.mail.api-key now exist in the Environment. A placeholder like ${db.password} or a record field bound to app.mail.api-key can use them.
Two details matter:
- Trailing slash: the path must end with
/forconfigtree:. Without it, Spring treats the location differently and your values won't load. - Wildcards:
configtree:/etc/config/*/imports every subdirectory as its own tree. This suits layouts where each secret has its own folder.
A config tree has an advantage over environment variables. A mounted file can be updated by the platform without exposing the value in docker inspect or the process environment listing.
Secret stores
For secrets that are shared across services or rotated often, import from a store at startup. Libraries such as Spring Cloud AWS (Secrets Manager, Parameter Store), Spring Cloud Vault, and Spring Cloud Azure register their own import prefixes. The pattern is the same:
spring:
config:
import: "optional:aws-secretsmanager:/prod/app/"Each library documents its own prefix and the permissions its credentials need. Check the exact syntax for your version. A store import also needs credentials to reach the store, so the bootstrap secret still comes from the platform, such as an IAM role, and not from your files.
Avoid the command line for secrets
This looks tempting but is a poor choice:
java -jar app.jar --spring.datasource.password=s3cret-valueCommand-line arguments appear in the process list (ps) for every user on the machine, and they land in shell history and often in CI logs. Environment variables are visible to the same user and to administrators, but they are not shown in a normal ps listing. Mounted files are the narrowest option. Use arguments for non-sensitive switches such as --spring.profiles.active=prod.
Preventing leaks after binding
A secret can still escape once it is in a bean. Check these points.
Record and class `toString`
A record generates a toString that prints every component. Logging the properties object would print the key:
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
@Validated
@ConfigurationProperties(prefix = "app.partner")
public record PartnerProperties(@NotBlank String url, @NotBlank String apiKey) {
@Override
public String toString() {
return "PartnerProperties[url=" + url + ", apiKey=***]";
}
}Validation with @NotBlank also helps. A missing secret fails startup immediately with a clear message, and that message names the property but not its value.
Actuator endpoints
If you expose the env or configprops Actuator endpoints, Spring Boot sanitizes values. In Spring Boot 3 all values are masked by default. You turn display on with management.endpoint.env.show-values and management.endpoint.configprops.show-values. Setting them to ALWAYS exposes everything, and WHEN_AUTHORIZED limits it to authorized users. Keep the default in production, and don't expose these endpoints on a public port.
Version control hygiene
- Add override files and
.envto.gitignorebefore the first commit. - If a secret was committed, rotate it. Rewriting history doesn't help once the repository has been cloned or pushed.
- Run a secret scanner in CI so a mistake is caught on the pull request.
Common errors
| Symptom | Likely cause |
|---|---|
| `Could not resolve placeholder 'X'` | The variable is not set in this process. Check the spelling and that the shell exported it. |
| `configtree:` imports nothing | Missing trailing `/`, or the directory isn't mounted in this environment. |
| Local file seems ignored | The path is relative to the working directory, not the jar. |
| Value from the file differs from the variable | Environment variables outrank packaged files. Check which source supplies the key. |
Exercise
A teammate adds password: prod-pass-123 to application-prod.yaml and commits it. Name two changes that fix the configuration going forward, and say what must also happen to the password itself.
Show answer
Replace the literal with a placeholder such as password: ${DB_PASSWORD} (or remove it and rely on SPRING_DATASOURCE_PASSWORD), and supply the value from the environment or a mounted secret through configtree: at deploy time. Add @NotBlank validation on the bound property so a missing value fails startup. The password has already been exposed in Git history, so it must be rotated.
Exercise
Why is optional:file:./local-overrides.yaml safe to include in the committed application.yaml, and which value wins if both files define app.mail.port?
Show answer
The optional: prefix lets startup continue when the file doesn't exist, as in CI and production. When the file does exist, the imported document takes precedence over the file that imports it, so the value in local-overrides.yaml wins.