Class ConfNG
- java.lang.Object
-
- org.confng.ConfNG
-
public class ConfNG extends Object
Main configuration management class for ConfNG.ConfNG provides a unified way to access configuration values from multiple sources with a defined precedence order. By default, it checks environment variables first, then system properties, followed by any loaded properties, JSON, YAML, or TOML files.
This class supports integration with secret managers like AWS Secrets Manager and HashiCorp Vault, providing secure access to sensitive configuration data.
Global vs Environment-Specific Configuration
ConfNG supports a powerful pattern for managing configurations across multiple environments by separating global/common settings from environment-specific overrides:
Global/Common Configuration
Define baseline configuration that applies to all environments in global configuration files:
- global.properties, global.json, global.yaml, global.toml
- common.properties, common.json, common.yaml, common.toml
// Load global configuration (applies to all environments) ConfNG.loadGlobalConfig();
Environment-Specific Configuration
Override global settings with environment-specific values (env1, env2, env3, etc.):
// Load environment-specific files (overrides global config) ConfNG.loadConfigForEnvironment("env1"); // Loads env1.properties, env1.json, env1.yaml, env1.toml // Or automatically detect environment from APP_ENV, ENVIRONMENT, or ENV variables String env = ConfNG.autoLoadConfig(); // Automatically loads config for detected environmentRecommended Loading Order
For best practices, load global configuration first, then environment-specific:
// 1. Load global/common configuration ConfNG.loadGlobalConfig(); // 2. Load environment-specific configuration (overrides global) ConfNG.loadConfigForEnvironment("prod");Example Configuration Structure
global.json (shared across all environments):
{ "api.timeout": "30", "retry.count": "3", "log.level": "INFO" }uat.json (UAT-specific overrides):
{ "api.url": "https://uat-api.example.com", "api.timeout": "60", "database.host": "uat-db.example.com" }Result for UAT: api.timeout=60 (overridden), retry.count=3 (inherited from global), log.level=INFO (inherited from global), plus UAT-specific api.url and database.host
Additional Configuration Patterns
Environment Sections Within Files
Store multiple environments in a single file with sections:
// Load specific environment section from a file ConfNG.loadJson("config.json", "uat"); // Loads only the "uat" section ConfNG.loadYaml("config.yaml", "prod"); // Loads only the "prod" section ConfNG.loadToml("config.toml", "qa"); // Loads only the "qa" sectionTestNG Integration
When using TestNG, the
TestNGParameterListenerautomatically loads global configuration followed by environment-specific configuration at suite startup. Simply add an "environment" or "env" parameter to your testng.xml:<suite name="My Test Suite"> <parameter name="environment" value="uat"/> ... </suite>
- Since:
- 1.0
- Author:
- Bharat Kumar Malviya, GitHub: github.com/imBharatMalviya
- See Also:
ConfNGKey,ConfigSource,TestNGParameterListener
-
-
Constructor Summary
Constructors Constructor Description ConfNG()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidaddSource(ConfigSource source)Adds a configuration source with automatic priority-based ordering.static StringautoLoadConfig()Automatically detects the current environment and loads appropriate configuration files.static voidclearSourcesAndUseDefaults()static List<ConfNGKey>discoverAllConfigKeys(String... basePackages)Discovers all ConfNGKey implementations in the classpath.static Stringget(ConfNGKey key)Gets a configuration value for the given key.static StringgetAllForDisplay(ConfNGKey... keys)Gets all configuration values for display purposes.static BooleangetBoolean(ConfNGKey key)Gets a configuration value as a boolean.static StringgetEnvironmentName()Detects the current environment name by checking multiple configuration keys in order.static StringgetForDisplay(ConfNGKey key)Gets a configuration value with masking for sensitive data.static IntegergetInt(ConfNGKey key)Gets a configuration value as an integer.static Set<String>getResolvedKeys()Gets all resolved configuration keys.static intgetResolvedValueCount()Gets the number of resolved configuration values.static booleanisResolved()Checks if configuration values have been resolved.static voidload(String filePath)Loads a configuration file by auto-detecting its type based on the file extension.static voidload(String filePath, String environment)Loads a configuration file with environment-specific section by auto-detecting its type.static voidloadConfigForEnvironment(String environment)Loads all environment-specific configuration files for the given environment.static voidloadGlobalConfig()Loads global/common configuration files that apply to all environments.static voidloadJson(String filePath)Loads a JSON file as a configuration source.static voidloadJson(String filePath, String environment)Loads a JSON file as a configuration source for a specific environment.static voidloadProperties(String filePath)Loads a properties file as a configuration source.static voidloadSecretSource(ConfigSource source)Loads a custom secret source.static voidloadToml(String filePath)Loads a TOML file as a configuration source.static voidloadToml(String filePath, String environment)Loads a TOML file as a configuration source for a specific environment.static voidloadYaml(String filePath)Loads a YAML file as a configuration source.static voidloadYaml(String filePath, String environment)Loads a YAML file as a configuration source for a specific environment.static voidrefresh()Forces re-resolution of all configuration values.static voidregisterSource(ConfigSource source)static voidregisterSourceAt(int precedenceIndex, ConfigSource source)static voidresolveAllValues()Resolves all configuration values from all sources according to precedence.static voidresolveAllValues(Set<String> keys)Resolves configuration values for the specified keys from all sources.
-
-
-
Method Detail
-
registerSource
public static void registerSource(ConfigSource source)
-
registerSourceAt
public static void registerSourceAt(int precedenceIndex, ConfigSource source)
-
addSource
public static void addSource(ConfigSource source)
Adds a configuration source with automatic priority-based ordering. Sources with higher priority values are placed earlier in the resolution chain.- Parameters:
source- the configuration source to add
-
clearSourcesAndUseDefaults
public static void clearSourcesAndUseDefaults()
-
load
public static void load(String filePath)
Loads a configuration file by auto-detecting its type based on the file extension. Supports .properties, .json, .yaml, .yml, and .toml files. Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it will be silently skipped.- Parameters:
filePath- path to the configuration file (filesystem or classpath)
-
load
public static void load(String filePath, String environment)
Loads a configuration file with environment-specific section by auto-detecting its type. Supports .json, .yaml, .yml, and .toml files with environment sections. Supports loading from both filesystem and classpath (including JAR resources). Properties files don't support environment sections. If the file doesn't exist, it will be silently skipped.- Parameters:
filePath- path to the configuration file (filesystem or classpath)environment- the environment section to load (e.g., "uat", "beta", "qa", "prod")
-
loadProperties
public static void loadProperties(String filePath)
Loads a properties file as a configuration source. Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it's silently skipped. If the file exists but is invalid, throws a runtime exception.- Parameters:
filePath- path to the properties file (filesystem or classpath)
-
loadJson
public static void loadJson(String filePath)
Loads a JSON file as a configuration source. Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it's silently skipped. If the file exists but is invalid, throws a runtime exception.- Parameters:
filePath- path to the JSON file (filesystem or classpath)
-
loadYaml
public static void loadYaml(String filePath)
Loads a YAML file as a configuration source. Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it's silently skipped. If the file exists but is invalid, throws a runtime exception.- Parameters:
filePath- path to the YAML file (filesystem or classpath)
-
loadToml
public static void loadToml(String filePath)
Loads a TOML file as a configuration source. Loads all top-level keys (not nested in environment sections). Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it's silently skipped. If the file exists but is invalid, throws a runtime exception.- Parameters:
filePath- path to the TOML file (filesystem or classpath)
-
loadToml
public static void loadToml(String filePath, String environment)
Loads a TOML file as a configuration source for a specific environment. Only configuration from the specified environment section is loaded. Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it's silently skipped. If the file exists but is invalid or the environment section doesn't exist, throws a runtime exception.- Parameters:
filePath- path to the TOML file (filesystem or classpath)environment- the environment section to load (e.g., "uat", "beta", "qa", "prod")
-
loadJson
public static void loadJson(String filePath, String environment)
Loads a JSON file as a configuration source for a specific environment. Only configuration from the specified environment section is loaded. Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it's silently skipped. If the file exists but is invalid or the environment section doesn't exist, throws a runtime exception.- Parameters:
filePath- path to the JSON file (filesystem or classpath)environment- the environment section to load (e.g., "uat", "beta", "qa", "prod")
-
loadYaml
public static void loadYaml(String filePath, String environment)
Loads a YAML file as a configuration source for a specific environment. Only configuration from the specified environment section is loaded. Supports loading from both filesystem and classpath (including JAR resources). If the file doesn't exist, it's silently skipped. If the file exists but is invalid or the environment section doesn't exist, throws a runtime exception.- Parameters:
filePath- path to the YAML file (filesystem or classpath)environment- the environment section to load (e.g., "uat", "beta", "qa", "prod")
-
loadGlobalConfig
public static void loadGlobalConfig()
Loads global/common configuration files that apply to all environments. Automatically looks for and loads the following files if they exist:- global.properties
- global.json
- global.yaml
- global.toml
- common.properties
- common.json
- common.yaml
- common.toml
Files that don't exist are silently skipped. This method should be called before loading environment-specific configuration to establish a baseline configuration that can be overridden by environment-specific values.
Example usage:
// Load global configuration first ConfNG.loadGlobalConfig(); // Then load environment-specific configuration (which can override global values) ConfNG.loadConfigForEnvironment("uat");
-
loadConfigForEnvironment
public static void loadConfigForEnvironment(String environment)
Loads all environment-specific configuration files for the given environment. Automatically looks for and loads the following files if they exist:- {environment}.properties
- {environment}.json
- {environment}.yaml
- {environment}.toml
Files that don't exist are silently skipped. This method provides a convenient way to load all configuration for a specific environment with a single call.
Note: For best practices, call
loadGlobalConfig()before this method to load global/common configuration that applies to all environments. Environment-specific values will override global values due to the loading order.- Parameters:
environment- the environment name (e.g., "env1", "env2", "env3")
-
autoLoadConfig
public static String autoLoadConfig()
Automatically detects the current environment and loads appropriate configuration files.The environment is detected by checking the following configuration keys in order (respecting ConfNG's source precedence):
- APP_ENV (case-insensitive: app_env, App_Env, etc.)
- ENVIRONMENT (case-insensitive: environment, Environment, etc.)
- ENV (case-insensitive: env, Env, etc.)
If no value is found in any configuration source, defaults to "local".
This method uses ConfNG's own configuration resolution system, which means the environment can be set via any configuration source (environment variables, system properties, TestNG parameters, configuration files, etc.) according to the standard precedence order.
Case Insensitivity: The key lookup is case-insensitive. For example, setting
export app_env=productionorexport APP_ENV=productionwill both work.Once the environment is detected, this method calls
loadConfigForEnvironment(String)to load all environment-specific configuration files.- Returns:
- the detected environment name
-
getEnvironmentName
public static String getEnvironmentName()
Detects the current environment name by checking multiple configuration keys in order.This method checks the following keys in order (case-insensitive), returning the first non-null, non-empty value:
- APP_ENV (or app_env, App_Env, etc.)
- ENVIRONMENT (or environment, Environment, etc.)
- ENV (or env, Env, etc.)
If none of these keys have a value, returns "local" as the default.
This method uses ConfNG's configuration resolution system, respecting source precedence. For example, if APP_ENV is set as a TestNG parameter, it will take precedence over APP_ENV set as an environment variable.
Case Insensitivity: The key lookup is case-insensitive, so APP_ENV, app_env, App_Env, etc. are all treated as the same key.
- Returns:
- the detected environment name, never null
-
loadSecretSource
public static void loadSecretSource(ConfigSource source)
Loads a custom secret source.- Parameters:
source- the custom configuration source to add
-
resolveAllValues
public static void resolveAllValues()
Resolves all configuration values from all sources according to precedence. This method is called automatically when needed but can be called manually to force immediate resolution of all values.
-
resolveAllValues
public static void resolveAllValues(Set<String> keys)
Resolves configuration values for the specified keys from all sources. If keys is null, attempts to discover all keys from known ConfNGKey implementations.- Parameters:
keys- specific keys to resolve, or null to discover all keys
-
get
public static String get(ConfNGKey key)
Gets a configuration value for the given key.- Parameters:
key- the configuration key- Returns:
- the configuration value, or the default value if not found
-
getInt
public static Integer getInt(ConfNGKey key)
Gets a configuration value as an integer.- Parameters:
key- the configuration key- Returns:
- the configuration value as integer, or null if not found and no default
- Throws:
IllegalArgumentException- if the value cannot be converted to integer
-
getBoolean
public static Boolean getBoolean(ConfNGKey key)
Gets a configuration value as a boolean.- Parameters:
key- the configuration key- Returns:
- the configuration value as boolean, or null if not found and no default
- Throws:
IllegalArgumentException- if the value cannot be converted to boolean
-
getForDisplay
public static String getForDisplay(ConfNGKey key)
Gets a configuration value with masking for sensitive data.- Parameters:
key- the configuration key- Returns:
- the configuration value, masked if sensitive
-
getAllForDisplay
public static String getAllForDisplay(ConfNGKey... keys)
Gets all configuration values for display purposes. Sensitive values are masked.- Parameters:
keys- the configuration keys to display- Returns:
- a formatted string showing all configuration values
-
discoverAllConfigKeys
public static List<ConfNGKey> discoverAllConfigKeys(String... basePackages)
Discovers all ConfNGKey implementations in the classpath.- Parameters:
basePackages- packages to scan, if empty scans entire classpath- Returns:
- list of discovered configuration keys
-
refresh
public static void refresh()
Forces re-resolution of all configuration values. Useful when configuration sources might have changed.
-
getResolvedValueCount
public static int getResolvedValueCount()
Gets the number of resolved configuration values.- Returns:
- number of resolved values
-
isResolved
public static boolean isResolved()
Checks if configuration values have been resolved.- Returns:
- true if values are resolved, false otherwise
-
-