⚙️ Configuration Governance, Type Safety & Hierarchical Cascade Management
In enterprise automated testing suites running across multi-tier deployment stages (Local Docker, Development, QA, Staging, and Production), hardcoding hostnames, ports, authentication credentials, and timeout ceilings inside test source files breaks maintainability and exposes sensitive infrastructure secrets. Standard java.util.Properties requires verbose file input stream handling, lacks native type conversion, returns untyped String values requiring error-prone parsing (e.g. Integer.parseInt()), and fails to provide default fallback values. The OWNER library (org.aeonbits.owner) solves this by introducing declarative, type-safe configuration mapping. By binding a simple Java interface to property sources with @Config.Sources, OWNER automatically evaluates a prioritized cascade—prioritizing command-line JVM arguments (-Denv=staging), falling back to OS environment variables, and defaulting to classpath properties files. In REST Assured, pairing OWNER with RequestSpecBuilder establishes an immutable, environment-agnostic configuration backbone.
OWNER LIBRARY PROPERTY RESOLUTION CASCADE (PRIORITY ORDER: TOP TO BOTTOM):
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ PRIORITY 1: COMMAND-LINE SYSTEM PROPERTIES (CLI ARGS) │
│ mvn clean test -Denv=staging -Dapi.timeout.ms=8000 -Dauth.token=ey... │
│ Evaluated first via "system:properties" ──► Highest override priority │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼ (If key is absent on CLI)
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ PRIORITY 2: OS ENVIRONMENT VARIABLES │
│ export API_BASE_URL="https://qa-api.nikita-infotech.com" │
│ Evaluated second via "system:env" ──► Ideal for Docker/Kubernetes CI/CD containers │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼ (If key is absent in OS env)
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ PRIORITY 3: DYNAMIC ENVIRONMENT-SPECIFIC PROPERTIES FILE │
│ classpath:config/${env}.properties (e.g., config/staging.properties) │
│ Evaluated dynamically based on the resolved -Denv parameter │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼ (If key is absent in env file)
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ PRIORITY 4: GLOBAL DEFAULT PROPERTIES FILE │
│ classpath:config/default.properties │
│ Baseline fallback configuration shared across all environments │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼ (If key is missing from all files)
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ PRIORITY 5: INLINE INTERFACE FALLBACK │
│ @DefaultValue("https://staging-api.nikita-infotech.com") │
│ Hard-coded safety net defined directly on interface methods ──► Prevents NullPointerException │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
EnvironmentConfig interface. Demonstrates mapping property keys using @Key, declaring fallbacks with @DefaultValue, configuring source cascades with @Config.Sources, and enforcing strict data types (String, int, boolean, URL).
package com.nikita.restassured.config;
import org.aeonbits.owner.Config;
import org.aeonbits.owner.Config.LoadPolicy;
import org.aeonbits.owner.Config.LoadType;
import org.aeonbits.owner.Config.Sources;
import java.net.URL;
// FIRST policy reads from the first source where the key is found
@LoadPolicy(LoadType.FIRST)
@Sources({
"system:properties", // 1. JVM -D flags (e.g. -Denv=qa)
"system:env", // 2. OS environment variables
"classpath:config/${env}.properties", // 3. Dynamic env file (staging.properties)
"classpath:config/default.properties" // 4. Default baseline properties
})
public interface EnvironmentConfig extends Config {
@Key("env")
@DefaultValue("staging")
String targetEnvironment();
@Key("api.base.url")
@DefaultValue("https://staging-api.nikita-infotech.com")
String apiBaseUrl();
@Key("api.base.path")
@DefaultValue("/v1")
String apiBasePath();
@Key("api.timeout.ms")
@DefaultValue("5000")
int apiTimeoutMs();
@Key("api.logging.enabled")
@DefaultValue("true")
boolean isLoggingEnabled();
@Key("auth.server.url")
@DefaultValue("https://auth.nikita-infotech.com")
URL authServerUrl(); // Automatically coerced to java.net.URL
@Key("auth.client.id")
@DefaultValue("sdet-automation-worker")
String authClientId();
@Key("auth.client.secret")
@DefaultValue("DefaultSecret#2026Key")
String authClientSecret();
@Key("tenant.region")
@DefaultValue("MH-PUNE-WEST")
String tenantRegion();
}
src/test/resources/config/. Contrasts default.properties, qa.properties, and staging.properties, showing how environment-specific overrides work.
# ==============================================================================
# FILE 1: src/test/resources/config/default.properties (GLOBAL BASELINE)
# ==============================================================================
api.base.path=/v1
api.timeout.ms=5000
api.logging.enabled=true
tenant.region=MH-PUNE-CENTRAL
auth.client.id=sdet-automation-worker
# ==============================================================================
# FILE 2: src/test/resources/config/qa.properties (QA ENVIRONMENT OVERRIDES)
# ==============================================================================
api.base.url=https://qa-api.nikita-infotech.com
auth.server.url=https://qa-auth.nikita-infotech.com
auth.client.id=qa-automation-worker
auth.client.secret=QaSecret#Pass2026
api.timeout.ms=8000
tenant.region=MH-PUNE-QA-CLUSTER
# ==============================================================================
# FILE 3: src/test/resources/config/staging.properties (STAGING ENVIRONMENT OVERRIDES)
# ==============================================================================
api.base.url=https://staging-api.nikita-infotech.com
auth.server.url=https://auth.nikita-infotech.com
auth.client.id=staging-automation-worker
auth.client.secret=StageSecure#Key2026
api.timeout.ms=6000
tenant.region=MH-PUNE-WEST
ConfigFactory.create(EnvironmentConfig.class) encapsulated inside a Bill Pugh Singleton to prevent re-parsing property files across parallel test threads.
package com.nikita.restassured.config;
import org.aeonbits.owner.ConfigFactory;
public class ConfigFactoryManager {
// Private constructor prevents external instantiation
private ConfigFactoryManager() {}
// Static inner class loaded only when getConfig() is first referenced
private static class SingletonHolder {
private static final EnvironmentConfig CONFIG_INSTANCE = ConfigFactory.create(
EnvironmentConfig.class,
System.getProperties(),
System.getenv()
);
}
/**
* Global access point for type-safe environment configuration
*/
public static EnvironmentConfig getConfig() {
return SingletonHolder.CONFIG_INSTANCE;
}
public static void printActiveConfiguration() {
EnvironmentConfig cfg = getConfig();
System.out.println("═════════════════════ [ACTIVE ENVIRONMENT CONFIG] ═════════════════════");
System.out.println("Target Environment : " + cfg.targetEnvironment().toUpperCase());
System.out.println("API Base URL : " + cfg.apiBaseUrl());
System.out.println("Base Path : " + cfg.apiBasePath());
System.out.println("Auth Server URL : " + cfg.authServerUrl());
System.out.println("Client ID : " + cfg.authClientId());
System.out.println("Timeout (ms) : " + cfg.apiTimeoutMs());
System.out.println("Logging Enabled : " + cfg.isLoggingEnabled());
System.out.println("Tenant Region : " + cfg.tenantRegion());
System.out.println("══════════════════════════════════════════════════════════════════════");
}
}
RequestSpecBuilder. Shows how base URIs, paths, timeout policies, and tenant headers are dynamically injected into specifications without hardcoded values.
package com.nikita.restassured.specs;
import com.nikita.restassured.config.ConfigFactoryManager;
import com.nikita.restassured.config.EnvironmentConfig;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.util.UUID;
public class OwnerDrivenSpecFactory {
public static RequestSpecification getEnvironmentDrivenSpec() {
// Read configuration from OWNER singleton
EnvironmentConfig config = ConfigFactoryManager.getConfig();
// Configure connection timeouts using OWNER integer property
RestAssuredConfig restAssuredConfig = RestAssuredConfig.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.connection.timeout", config.apiTimeoutMs())
.setParam("http.socket.timeout", config.apiTimeoutMs()));
RequestSpecBuilder builder = new RequestSpecBuilder()
.setConfig(restAssuredConfig)
.setBaseUri(config.apiBaseUrl())
.setBasePath(config.apiBasePath())
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.addHeader("X-Tenant-Region", config.tenantRegion())
.addHeader("X-Correlation-Id", "TRACE-" + UUID.randomUUID().toString().substring(0, 8))
.addHeader("X-Client-Platform", "REST-Assured-Masterclass");
if (config.isLoggingEnabled()) {
builder.log(LogDetail.URI);
}
return builder.build();
}
}
Converter<T>. Demonstrates converting string property values like "15s" into a java.time.Duration, and parsing comma-separated strings into a List<String>.
package com.nikita.restassured.config;
import org.aeonbits.owner.Config;
import org.aeonbits.owner.Config.ConverterClass;
import org.aeonbits.owner.Config.DefaultValue;
import org.aeonbits.owner.Config.Key;
import org.aeonbits.owner.Converter;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
// Custom Converter: Converts string representations like "10s", "5m" to java.time.Duration
class DurationConverter implements Converter<Duration> {
@Override
public Duration convert(Method method, String input) {
if (input == null || input.trim().isEmpty()) {
return Duration.ofSeconds(5);
}
String sanitized = input.trim().toLowerCase();
if (sanitized.endsWith("s")) {
return Duration.ofSeconds(Long.parseLong(sanitized.replace("s", "")));
} else if (sanitized.endsWith("m")) {
return Duration.ofMinutes(Long.parseLong(sanitized.replace("m", "")));
} else if (sanitized.endsWith("ms")) {
return Duration.ofMillis(Long.parseLong(sanitized.replace("ms", "")));
}
return Duration.ofSeconds(Long.parseLong(sanitized));
}
}
public interface AdvancedConfig extends Config {
@Key("api.retry.timeout")
@DefaultValue("10s")
@ConverterClass(DurationConverter.class)
Duration retryTimeout();
// Built-in separator converter: splits comma-delimited strings into typed List
@Key("api.supported.routes")
@DefaultValue("/students,/curriculum,/billing,/auth")
@Config.Separator(",")
List<String> supportedRoutes();
@Key("api.rate.limit.per.second")
@DefaultValue("50")
int rateLimitPerSecond();
}
-Denv=qa, overriding single parameters like -Dapi.timeout.ms=10000, and verifying the CLI cascade precedence.
# ==============================================================================
# COMMAND 1: RUN SUITE TARGETING QA ENVIRONMENT
# ==============================================================================
# Reads src/test/resources/config/qa.properties automatically:
$ mvn clean test -Denv=qa
# ==============================================================================
# COMMAND 2: RUN SUITE ON STAGING WITH CUSTOM AD-HOC TIMEOUT OVERRIDE
# ==============================================================================
# Overrides api.timeout.ms to 12000 on the command line; takes precedence over file!
$ mvn clean test -Denv=staging -Dapi.timeout.ms=12000
# ==============================================================================
# COMMAND 3: GRADLE EQUIVALENT WITH CLI OVERRIDES
# ==============================================================================
$ ./gradlew test -Denv=prod -Dapi.logging.enabled=false
package com.nikita.restassured.config;
import org.testng.Assert;
import org.testng.annotations.Test;
public class CliOverrideVerificationTest {
@Test(description = "Verify that command-line properties take precedence over properties files")
public void testCliSystemPropertyPrecedence() {
EnvironmentConfig config = ConfigFactoryManager.getConfig();
System.out.println("[*] Active Environment : " + config.targetEnvironment());
System.out.println("[*] Active Base URL : " + config.apiBaseUrl());
System.out.println("[*] Active Timeout (ms) : " + config.apiTimeoutMs());
Assert.assertNotNull(config.apiBaseUrl(), "Base URL must not be null!");
Assert.assertTrue(config.apiTimeoutMs() > 0, "Timeout must be a positive integer!");
}
}
package com.nikita.restassured.tests;
import com.nikita.restassured.config.ConfigFactoryManager;
import com.nikita.restassured.config.EnvironmentConfig;
import com.nikita.restassured.specs.OwnerDrivenSpecFactory;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
public class OwnerDrivenApiTest {
private RequestSpecification envSpec;
private EnvironmentConfig config;
@BeforeClass
public void setupEnvironment() {
// Log active configuration settings
ConfigFactoryManager.printActiveConfiguration();
config = ConfigFactoryManager.getConfig();
// Assemble request specification from OWNER properties
envSpec = OwnerDrivenSpecFactory.getEnvironmentDrivenSpec();
}
@Test(description = "Execute API query using dynamically resolved OWNER configuration")
public void testStudentLookupUsingOwnerConfig() {
given()
// Bind environment specification assembled from OWNER properties:
.spec(envSpec)
.pathParam("studentId", "STU-88219")
.when()
.get("/students/{studentId}")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"))
.body("data.fullName", equalTo("Nikita Sharma"))
// Validate server reflects configured tenant region:
.header("X-Tenant-Assigned", notNullValue());
System.out.printf("[✔] Completed test against [%s] environment (%s).%n",
config.targetEnvironment().toUpperCase(), config.apiBaseUrl());
}
}
@DefaultValue.
package com.nikita.restassured.config;
import org.aeonbits.owner.Config;
import org.aeonbits.owner.Config.DefaultValue;
import org.aeonbits.owner.Config.Key;
import org.aeonbits.owner.Config.Sources;
import org.aeonbits.owner.ConfigFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
public class OwnerTriageTest {
// ==========================================================================
// PITFALL 1: MISSING PROPERTY WITHOUT @DefaultValue
// If a property key is absent from all declared sources and lacks a
// @DefaultValue annotation, OWNER returns null for objects or 0/false
// for primitives. This can lead to unexpected NullPointerExceptions!
//
// SOLUTION: Always declare sensible fallback defaults with @DefaultValue!
// ==========================================================================
@Sources({ "classpath:config/non-existent-file.properties" })
interface TriageConfig extends Config {
@Key("missing.property.no.default")
String missingPropertyWithoutDefault();
@Key("safe.property.with.default")
@DefaultValue("safe-fallback-value")
String safePropertyWithDefault();
@Key("port.number")
@DefaultValue("8080")
int portNumber();
}
@Test(description = "Verify that @DefaultValue prevents null pointer exceptions on missing keys")
public void testVerifyFallbackBehavior() {
TriageConfig config = ConfigFactory.create(TriageConfig.class);
// 1. Missing property without default returns null:
Assert.assertNull(config.missingPropertyWithoutDefault(),
"Property without default must return null when key is absent!");
// 2. Safe property with default returns the configured default:
Assert.assertEquals(config.safePropertyWithDefault(), "safe-fallback-value",
"@DefaultValue must supply fallback when file is absent!");
// 3. Numeric property returns parsed integer:
Assert.assertEquals(config.portNumber(), 8080);
System.out.println("[✔] Fallback validation passed: @DefaultValue successfully supplied default values.");
}
}
OWNER LIBRARY CONFIGURATION SPECIFICATION MATRIX:
┌─────────────────────────┬──────────────────────────────┬──────────────────┬───────────────────────────────┐
│ ANNOTATION / METHOD │ SYNTAX EXAMPLE │ TARGET SCOPE │ PRIMARY OPERATIONAL PURPOSE │
├─────────────────────────┼──────────────────────────────┼──────────────────┼───────────────────────────────┤
│ @Config.Sources │ @Sources({"system:prop",..}) │ Interface Level │ Declares prioritized sources │
│ @Config.LoadPolicy │ @LoadPolicy(LoadType.FIRST) │ Interface Level │ Halts on first matching key │
│ @Key │ @Key("api.base.url") │ Method Level │ Maps method to property key │
│ @DefaultValue │ @DefaultValue("https://..") │ Method Level │ Fallback if key is missing │
│ @ConverterClass │ @ConverterClass(Custom.class)│ Method Level │ Custom type coercion parser │
│ @Config.Separator │ @Separator(",") │ Method Level │ Splits strings into List/Array│
│ ConfigFactory.create() │ ConfigFactory.create(Cfg.cls)│ Runtime Factory │ Instantiates proxy interface │
│ system:properties │ "system:properties" │ In @Sources │ Reads JVM -D flags (CLI) │
│ system:env │ "system:env" │ In @Sources │ Reads OS environment variables│
│ classpath:file.prop │ "classpath:config/${env}.prop│ In @Sources │ Reads resource file on path │
│ Variable Expansion │ ${env} in path or value │ Dynamic Token │ Expands runtime property value│
├─────────────────────────┴──────────────────────────────┴──────────────────┴───────────────────────────────┤
│ TOP 5 OWNER CONFIGURATION BEST PRACTICES: │
│ 1. Always prioritize "system:properties": Ensure CI/CD can override any setting via -D command flags. │
│ 2. Annotate every method with @DefaultValue: Prevent NullPointerExceptions when properties are missing. │
│ 3. Use Bill Pugh Singleton for ConfigFactory: Avoid re-parsing properties on every parallel test. │
│ 4. Leverage built-in type coercion: Declare methods as int, boolean, URL rather than raw Strings. │
│ 5. Keep sensitive secrets out of committed files: Supply tokens and passwords via OS environment vars. │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────┘