Configuration & Profiles

🌿 Spring BootLesson 10Intermediate

Spring Boot's externalized configuration lets you manage settings for different environments (dev, test, prod) without changing code. @ConfigurationProperties provides a type-safe, IDE-friendly way to bind configuration values to Java objects.

1 @ConfigurationProperties
Java — AppProperties.java
@ConfigurationProperties(prefix = "app")
@Component
@Validated
@Data
public class AppProperties {

    @NotBlank
    private String name;

    @NotBlank
    private String version;

    private Security security = new Security();
    private Cors cors = new Cors();

    @Data
    public static class Security {
        @NotBlank
        private String jwtSecret;

        @Positive
        private long accessTokenExpiry  = 900;    // 15 minutes

        @Positive
        private long refreshTokenExpiry = 604800; // 7 days
    }

    @Data
    public static class Cors {
        private List<String> allowedOrigins = List.of("http://localhost:3000");
        private List<String> allowedMethods = List.of("GET","POST","PUT","PATCH","DELETE");
    }
}
YAML — application.yml
app:
  name: My Spring API
  version: 1.0.0
  security:
    jwt-secret: ${JWT_SECRET}   # Read from env variable
    access-token-expiry: 900
    refresh-token-expiry: 604800
  cors:
    allowed-origins:
      - https://myapp.com
      - https://admin.myapp.com
2 Spring Profiles
Shell — Profile-Specific Files
resources/
  application.yml           # Common config
  application-dev.yml       # Dev overrides
  application-prod.yml      # Prod overrides
  application-test.yml      # Test overrides

# Activate profile:
# Via env: SPRING_PROFILES_ACTIVE=prod
# Via CLI: java -jar app.jar --spring.profiles.active=prod
# Via code: @ActiveProfiles("test") in tests
3 Code Challenge
Challenge: Create a RateLimitProperties configuration class with prefix = "app.rate-limit" containing maxRequests, windowSeconds, and a map of endpointOverrides (e.g., auth: 10). Wire it into a rate-limiting filter.