Dotenv Config - VittorioDeMarzi/hero-beans GitHub Wiki
Here’s a small documentation for your DotenvConfig
class, focusing on how to use dotenv, why we use it, and why this configuration is set up this way.
📌 Using dotenv in a Spring/Kotlin Project
1. What is dotenv?
dotenv
is a library that loads environment variables from a .env
file into your application at runtime.
The .env
file typically contains configuration values such as database credentials, API keys, and other settings that should not be hardcoded in the codebase.
Example .env
:
TOKEN_SECRET_KEY=super-secret-key
TOKEN_EXPIRE_LENGTH=3600
SPRING_DATASOURCE_USERNAME=myuser
SPRING_DATASOURCE_PASSWORD=mypassword
2. Why use dotenv?
- Security: Keeps sensitive data out of source code and away from version control (e.g., GitHub).
- Portability: Makes it easy to configure the app differently for development, testing, and production without changing the code.
- Convenience: Allows local development without needing to set OS-level environment variables.
3. How this configuration works
-
@Configuration
Marks the class as a Spring configuration component so it’s loaded at application startup. -
@PostConstruct
RunsloadDotenv()
after the bean is created but before the application is fully started — ensuring variables are available early in the lifecycle. -
Dotenv.configure().ignoreIfMissing().ignoreIfMalformed().load()
.ignoreIfMissing()
→ Prevents errors if.env
is not present (useful for production where variables are set in the system)..ignoreIfMalformed()
→ Ignores syntax errors in.env
instead of failing startup..load()
→ Loads all key-value pairs from.env
.
-
dotenv.entries().forEach { System.setProperty(it.key, it.value) }
This copies all loaded variables into Java System Properties, so they can be accessed with Spring’s property resolution syntax:spring.datasource.username=${SPRING_DATASOURCE_USERNAME}
-
Logging
- Logs how many variables were loaded for transparency.
- Logs a warning if the file can’t be loaded, but doesn’t crash the app (important for environments without
.env
).
4. How to use in your project
-
Add
dotenv
dependency (e.g., in Gradle):implementation("io.github.cdimascio:dotenv-kotlin:6.4.1")
-
Create a
.env
file in the root of your project. -
Add
.env
to.gitignore
to avoid committing secrets:.env
-
Reference variables in
application.properties
orapplication.yml
:security.jwt.token.secret-key=${TOKEN_SECRET_KEY} security.jwt.token.expire-length=${TOKEN_EXPIRE_LENGTH}
5. Why configure it like this
- Safe defaults: Ignores missing/malformed files to avoid breaking deployments.
- Spring-friendly: Makes
.env
values available to Spring property resolution early. - Cross-environment: Works in local development and in production without changing code.
- Fail-soft: Logs issues but doesn’t stop application unless critical.