Environment Variables
Environment variables store configuration values outside your code. They're the standard way to handle secrets and environment-specific settings.
Why Environment Variables?
# BAD: Secrets in code (NEVER do this)
spring:
datasource:
password: mySecretPassword123 # Committed to Git!
# GOOD: Secrets in environment variables
spring:
datasource:
password: ${DB_PASSWORD} # Value set at deployment time
Setting Environment Variables
# Linux/Mac
export DB_PASSWORD=mySecretPassword123
export JWT_SECRET=myJwtSecretKey456
java -jar app.jar
# Windows CMD
set DB_PASSWORD=mySecretPassword123
java -jar app.jar
# Windows PowerShell
$env:DB_PASSWORD="mySecretPassword123"
java -jar app.jar
# Docker
docker run -e DB_PASSWORD=mySecretPassword123 myapp
# Kubernetes (Secret)
kubectl create secret generic db-secret --from-literal=password=mySecretPassword123
Accessing in Spring Boot
# application.yml — reference env vars with defaults
spring:
datasource:
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:mydb}
username: ${DB_USERNAME:postgres}
password: ${DB_PASSWORD:}
app:
jwt:
secret: ${JWT_SECRET:}
expiration: ${JWT_EXPIRATION:86400000}
Standard Environment Variables
| Variable | Purpose |
|---|---|
DB_HOST |
Database hostname |
DB_PORT |
Database port |
DB_NAME |
Database name |
DB_USERNAME |
Database username |
DB_PASSWORD |
Database password (SECRET) |
JWT_SECRET |
JWT signing key (SECRET) |
API_KEY |
External API key (SECRET) |
LOG_LEVEL |
Logging level |
SPRING_PROFILES_ACTIVE |
Active profile |
Security Rules
- Never commit secrets to Git — use .gitignore
- Never log secrets — mask them in application.yml
- Rotate secrets regularly — change passwords periodically
- Use secrets managers — AWS Secrets Manager, HashiCorp Vault
- Least privilege — database user with minimal permissions
Spring Boot .env File (Development Only)
# .env (NEVER commit to Git)
DB_PASSWORD=localdevpassword
JWT_SECRET=dev-only-secret-key
<!-- pom.xml — use dotenv for local dev -->
<dependency>
<groupId>me.paulschwarz</groupId>
<artifactId>spring-dotenv</artifactId>
<version>4.0.0</version>
</dependency>
Best Practices
Key Principles
- Follow SOLID principles
- Write clean, readable code
- Test thoroughly
- Document decisions
- Monitor in production
Implementation
- Start simple, refactor as needed
- Use established patterns
- Consider trade-offs
- Review with peers
Continuous Improvement
- Learn from incidents
- Update documentation
- Share knowledge
- Mentor others
Key Points
- Understanding Environment Variables is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Environment Variables in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Environment Variables implementation
// Key aspects: validation, error handling, logging, testing
public class EnvironmentVariables {
// Production-ready implementation
}Identify and handle edge cases for Environment Variables. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Environment Variables. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. How do you reference an environment variable in Spring Boot YAML?
2. Which environment variable should NEVER be committed to Git?
3. What is the primary purpose of Environment Variables?
4. What is a common mistake when implementing Environment Variables?
Flashcards
Question
How do you reference env vars in Spring YAML?
Click to reveal answer
Answer
${ENV_VAR_NAME} or ${ENV_VAR:defaultValue}
Question
What are environment variable security rules?
Click to reveal answer
Answer
Never commit secrets, never log them, rotate regularly, use secrets managers
Question
What is Environment Variables?
Click to reveal answer
Answer
Environment Variables is a key concept in backend development.
Question
When to use Environment Variables?
Click to reveal answer
Answer
Use Environment Variables when building production systems that require reliability, scalability, and maintainability.
Question
Environment Variables best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Environment variables keep secrets out of source code
- 2.Spring Boot uses ${ENV_VAR} syntax in YAML
- 3.Never commit DB_PASSWORD, JWT_SECRET to Git
- 4.Use secrets managers in production (AWS Secrets Manager, Vault)
- 5..env files are for local dev only — never commit them
Interview Tips
- •Know how to set and reference env vars in Spring Boot
- •Be ready to discuss secrets management strategy
- •Understand why hardcoded secrets are dangerous
Cheat Sheet
Environment Variables
- YAML Reference: ${ENV_VAR} or ${ENV_VAR:defaultValue}
- Set: export (Linux), $env: (PowerShell), -e (Docker)
- Secrets: DB_PASSWORD, JWT_SECRET — NEVER commit
- Production: AWS Secrets Manager, HashiCorp Vault