Skip to content
beginnerPhase ·

Environment Variables

Use environment variables for secrets and environment-specific config.

25m
0 problems
Topic Progress0%

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

  1. Never commit secrets to Git — use .gitignore
  2. Never log secrets — mask them in application.yml
  3. Rotate secrets regularly — change passwords periodically
  4. Use secrets managers — AWS Secrets Manager, HashiCorp Vault
  5. 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

  1. Follow SOLID principles
  2. Write clean, readable code
  3. Test thoroughly
  4. Document decisions
  5. 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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0/3solved
Implement Environment Variables

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
}
Environment Variables Edge Cases

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, idempotency
Environment Variables Testing Strategy

Write 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 injection

Quiz

1. How do you reference an environment variable in Spring Boot YAML?

Question 1 options

2. Which environment variable should NEVER be committed to Git?

Question 2 options

3. What is the primary purpose of Environment Variables?

Question 3 options

4. What is a common mistake when implementing Environment Variables?

Question 4 options

Flashcards

Question

How do you reference env vars in Spring YAML?

Answer

${ENV_VAR_NAME} or ${ENV_VAR:defaultValue}

Question

What are environment variable security rules?

Answer

Never commit secrets, never log them, rotate regularly, use secrets managers

Question

What is Environment Variables?

Answer

Environment Variables is a key concept in backend development.

Question

When to use Environment Variables?

Answer

Use Environment Variables when building production systems that require reliability, scalability, and maintainability.

Question

Environment Variables best practices

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