Spring › Feature

Loading .env files in Spring Boot without extra libraries

Load local .env files natively using Spring Boot's spring.config.import, with property precedence rules, production fail-fast setup, and common pitfalls.

Loading .env files in Spring Boot without extra libraries

Spring Boot 2.4 introduced spring.config.import, which lets you load local .env files directly without adding third-party libraries or IDE plugins. This post covers how the built-in loader works, how property precedence resolves, how to enforce fail-fast startup in production, and the three gotchas that trip teams up.

Tested with Spring Boot 3.x (supported since Spring Boot 2.4+).

Why use built-in config import instead of plugins or libraries

Local development always involves secrets you don’t want in Git: database passwords, JWT signing keys, and third-party API keys. A .env file is the simplest way to keep them out of version control, but Spring Boot doesn’t read .env files automatically.

Teams usually reach for dotenv-java or an IntelliJ plugin like EnvFile. Both come with friction: IDE plugins don’t run when you launch the app from the terminal with ./gradlew bootRun, and third-party libraries add another dependency to track across Spring Boot upgrades.

Aspectspring.config.import (built-in)dotenv-java / third-partyIDE plugin (EnvFile)
Extra dependencyNoneBuild dependency requiredIDE plugin required
CLI (bootRun) supportSupportedSupportedNot supported
Spring integrationNative Environment property sourceManual bootstrap or listenerInjects OS env vars at launch
Parsing syntaxJava .propertiesShell .envVaries by plugin

Built-in spring.config.import keeps IDE runs and CLI runs identical with zero extra dependencies. That said, don’t use it if your .env files rely heavily on shell-specific syntax like variable expansion (FOO=${BAR}), export prefixes, or multiline double-quoted values—a dedicated dotenv parser is a better fit there.

How ConfigDataEnvironmentPostProcessor loads .env and resolves precedence

At startup, ConfigDataEnvironmentPostProcessor reads spring.config.import and delegates optional:file:.env[.properties] to StandardConfigDataLocationResolver. Each piece of that string has a specific job:

  • optional:: Tells Spring Boot to continue booting if .env doesn’t exist (essential for CI and Docker).
  • file:.env: Looks for .env on the local filesystem rather than the classpath.
  • [.properties]: Gives PropertiesPropertySourceLoader a format hint, since .env has no file extension.

Spring Boot registers the parsed key-value pairs as a PropertySource inside the Environment. When resolving a placeholder like ${JWT_SECRET:default}, precedence flows in this order:

  1. OS environment variables (systemEnvironment): Values injected via docker run -e, Kubernetes Secrets, or CI environment variables always win.
  2. Imported .env file: External files imported via spring.config.import override the application.yml that declared them.
  3. application.yml fallback defaults: Inline defaults (${KEY:default}) apply only when neither the OS environment nor .env defines the key.

Because of this hierarchy, local runs pick up .env automatically, while production containers without a .env file read straight from OS environment variables with no code changes.

Local defaults and production fail-fast setup

A clean pattern is to keep safe dummy defaults in the shared application.yml for local development, and strip those defaults in application-prod.yml so production fails fast if a required secret is missing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# src/main/resources/application.yml
spring:
  application:
    name: portfolio

  config:
    import: optional:file:.env[.properties]

  profiles:
    default: local

jwt:
  secret: ${JWT_SECRET:local-dev-secret-key-for-testing-only}
  issuer: ${JWT_ISSUER:localhost}
  access-expiry: ${JWT_ACCESS_EXPIRATION:3600}
  refresh-expiry: ${JWT_REFRESH_EXPIRATION:604800}

storage:
  imgbb:
    api-key: ${IMGBB_API_KEY:dummy-api-key}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# src/main/resources/application-prod.yml
spring:
  datasource:
    url: ${DATABASE_URL}
    username: ${DATABASE_USERNAME}
    password: ${DATABASE_PASSWORD}
    driver-class-name: ${DATABASE_DRIVER:org.postgresql.Driver}

  data:
    redis:
      host: ${REDIS_HOST:localhost}
      port: ${REDIS_PORT:6379}
      database: ${REDIS_DATABASE:0}
      username: ${REDIS_USERNAME:}
      password: ${REDIS_PASSWORD:}

jwt:
  secret: ${JWT_SECRET}

When running with the prod profile, omitting DATABASE_URL or JWT_SECRET immediately aborts startup with IllegalArgumentException: Could not resolve placeholder instead of silently booting with a dummy key.

To share the expected variable names with teammates, commit a blank .env.template file to Git and ignore .env:

1
2
3
# .env.template (committed to Git)
JWT_SECRET=
IMGBB_API_KEY=
# .gitignore
.env

New teammates just copy the template and fill in their local values:

1
cp .env.template .env

Three pitfalls to watch out for

1. Forgetting optional: breaks CI and Docker

If you write file:.env[.properties] without the optional: prefix, Spring Boot throws ConfigDataLocationNotFoundException whenever .env is absent. That immediately breaks CI pipelines and production Docker images. Always include optional: for local-only files.

2. Quotes and backslashes follow Java .properties rules

Shell loaders and Node.js dotenv strip surrounding quotes ("..."). PropertiesPropertySourceLoader does not—it follows Java .properties syntax, so quotes stay inside the value string.

1
2
3
4
5
# Wrong: quotes become part of the resolved value
JWT_SECRET="my-secret-key"

# Correct: raw value with no surrounding quotes
JWT_SECRET=my-secret-key

Stray quotes in API keys or JWT secrets cause silent 401 Unauthorized responses or signature validation failures. Also remember that Java .properties treats backslashes (\) as escape characters, so escape literal backslashes as \\.

3. Relative paths depend on the JVM working directory

file:.env resolves relative to the JVM’s current working directory, not necessarily your Git repository root. If you run a submodule from a subdirectory or invoke java -jar from another folder, Spring Boot won’t find .env. Either set your IDE run configuration’s working directory to the repo root, or list both locations:

1
2
3
spring:
  config:
    import: optional:file:.env[.properties],optional:file:../.env[.properties]

Summary checklist

Combining spring.config.import: optional:file:.env[.properties] with a committed .env.template, .gitignore, and fail-fast production overrides keeps local setup simple without compromising production safety.

  • Prefix local .env imports with optional: so CI and containers boot cleanly without the file.
  • Omit surrounding quotes around values in .env and double-escape any literal backslashes.
  • Remove fallback defaults for secrets in application-prod.yml so missing env vars fail at startup.
  • Verify the working directory in multi-module setups if .env lives at the repository root.
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources including Java properties files, YAML files, environment variables, and command-line arguments.
This post is licensed under CC BY 4.0 by the author.