0
# Configuration Access
1
2
Configuration access provides the core API for retrieving values from Config objects using dot-separated path expressions. The Config interface offers type-safe getters with automatic conversion and comprehensive support for nested structures.
3
4
## Path-Based Access
5
6
### Basic Value Getters
7
8
Retrieve primitive configuration values with automatic type conversion.
9
10
```java { .api }
11
public boolean getBoolean(String path);
12
public Number getNumber(String path);
13
public int getInt(String path);
14
public long getLong(String path);
15
public double getDouble(String path);
16
public String getString(String path);
17
public <T extends Enum<T>> T getEnum(Class<T> enumClass, String path);
18
```
19
20
**Usage Examples:**
21
22
```java
23
Config config = ConfigFactory.load();
24
25
// Basic value access
26
boolean debugMode = config.getBoolean("app.debug");
27
int serverPort = config.getInt("server.port");
28
String dbUrl = config.getString("database.url");
29
double timeout = config.getDouble("client.timeout");
30
31
// Enum access
32
LogLevel level = config.getEnum(LogLevel.class, "logging.level");
33
```
34
35
### Duration and Time Access
36
37
Retrieve time-based values with support for various time units and formats.
38
39
```java { .api }
40
public Duration getDuration(String path);
41
public Duration getDuration(String path, TimeUnit unit);
42
public long getDuration(String path, TimeUnit unit);
43
public Period getPeriod(String path);
44
public TemporalAmount getTemporal(String path);
45
```
46
47
**Usage Examples:**
48
49
```java
50
// Duration access (supports formats like "30 seconds", "5 minutes", "2 hours")
51
Duration cacheTimeout = config.getDuration("cache.timeout");
52
Duration connectTimeout = config.getDuration("http.connect-timeout");
53
54
// Duration in specific units
55
long timeoutMillis = config.getDuration("timeout", TimeUnit.MILLISECONDS);
56
long retryDelaySeconds = config.getDuration("retry.delay", TimeUnit.SECONDS);
57
58
// Period access (supports formats like "2 days", "1 week", "3 months")
59
Period archiveAfter = config.getPeriod("data.archive-after");
60
61
// Temporal amount (Duration or Period)
62
TemporalAmount interval = config.getTemporal("scheduler.interval");
63
```
64
65
### Memory Size Access
66
67
Retrieve memory/byte size values with automatic unit conversion.
68
69
```java { .api }
70
public Long getBytes(String path);
71
public ConfigMemorySize getMemorySize(String path);
72
```
73
74
**Usage Examples:**
75
76
```java
77
// Memory size access (supports formats like "128MB", "4GB", "1024KB")
78
Long maxHeapBytes = config.getBytes("jvm.max-heap");
79
ConfigMemorySize bufferSize = config.getMemorySize("buffer.size");
80
81
// ConfigMemorySize provides additional methods
82
long bufferBytes = bufferSize.toBytes();
83
```
84
85
### Structured Data Access
86
87
Access nested configuration objects and convert to Config instances.
88
89
```java { .api }
90
public Object getAnyRef(String path);
91
public ConfigValue getValue(String path);
92
public ConfigObject getObject(String path);
93
public Config getConfig(String path);
94
```
95
96
**Usage Examples:**
97
98
```java
99
// Nested config access
100
Config dbConfig = config.getConfig("database");
101
String dbHost = dbConfig.getString("host");
102
int dbPort = dbConfig.getInt("port");
103
104
// Raw value access
105
ConfigValue rawValue = config.getValue("app.feature-flags");
106
Object unwrapped = config.getAnyRef("external-service.config");
107
108
// Object access
109
ConfigObject serverObj = config.getObject("server");
110
```
111
112
## List Access
113
114
### Typed List Getters
115
116
Retrieve lists of specific types with automatic element conversion.
117
118
```java { .api }
119
public ConfigList getList(String path);
120
public List<Boolean> getBooleanList(String path);
121
public List<Number> getNumberList(String path);
122
public List<Integer> getIntList(String path);
123
public List<Long> getLongList(String path);
124
public List<Double> getDoubleList(String path);
125
public List<String> getStringList(String path);
126
public <T extends Enum<T>> List<T> getEnumList(Class<T> enumClass, String path);
127
```
128
129
**Usage Examples:**
130
131
```java
132
// String lists
133
List<String> allowedHosts = config.getStringList("security.allowed-hosts");
134
List<String> enabledFeatures = config.getStringList("app.features");
135
136
// Numeric lists
137
List<Integer> ports = config.getIntList("server.ports");
138
List<Double> coefficients = config.getDoubleList("algorithm.coefficients");
139
140
// Boolean lists
141
List<Boolean> featureToggles = config.getBooleanList("features.enabled");
142
143
// Enum lists
144
List<Protocol> protocols = config.getEnumList(Protocol.class, "network.protocols");
145
```
146
147
### Advanced List Access
148
149
Access lists of complex objects and mixed types.
150
151
```java { .api }
152
public List<Object> getAnyRefList(String path);
153
public List<ConfigValue> getConfigValueList(String path);
154
public List<ConfigObject> getObjectList(String path);
155
public List<Config> getConfigList(String path);
156
```
157
158
**Usage Examples:**
159
160
```java
161
// Lists of objects
162
List<Config> servers = config.getConfigList("load-balancer.servers");
163
for (Config server : servers) {
164
String host = server.getString("host");
165
int port = server.getInt("port");
166
double weight = server.getDouble("weight");
167
}
168
169
// Lists of raw objects
170
List<Object> mixedValues = config.getAnyRefList("data.mixed-array");
171
172
// Lists of ConfigObjects
173
List<ConfigObject> policies = config.getObjectList("security.policies");
174
```
175
176
### Duration and Memory Lists
177
178
Access lists of time and memory values.
179
180
```java { .api }
181
public List<Duration> getDurationList(String path);
182
public List<Duration> getDurationList(String path, TimeUnit unit);
183
public List<Long> getDurationList(String path, TimeUnit unit);
184
public List<Long> getBytesList(String path);
185
public List<ConfigMemorySize> getMemorySizeList(String path);
186
```
187
188
**Usage Examples:**
189
190
```java
191
// Duration lists
192
List<Duration> retryIntervals = config.getDurationList("retry.intervals");
193
List<Long> timeoutsMs = config.getDurationList("timeouts", TimeUnit.MILLISECONDS);
194
195
// Memory size lists
196
List<Long> cacheSizes = config.getBytesList("cache.sizes");
197
List<ConfigMemorySize> bufferSizes = config.getMemorySizeList("buffers");
198
```
199
200
## Path Existence and Navigation
201
202
### Path Checking
203
204
Check for path existence and null values.
205
206
```java { .api }
207
public boolean hasPath(String path);
208
public boolean hasPathOrNull(String path);
209
public boolean getIsNull(String path);
210
public boolean isEmpty();
211
```
212
213
**Usage Examples:**
214
215
```java
216
// Check if path exists and is not null
217
if (config.hasPath("optional.feature")) {
218
boolean enabled = config.getBoolean("optional.feature");
219
}
220
221
// Check if path exists (including null values)
222
if (config.hasPathOrNull("nullable.setting")) {
223
if (config.getIsNull("nullable.setting")) {
224
// Handle null case
225
} else {
226
String value = config.getString("nullable.setting");
227
}
228
}
229
230
// Check if config is empty
231
if (config.isEmpty()) {
232
// Handle empty configuration
233
}
234
```
235
236
### Structure Navigation
237
238
Navigate and inspect configuration structure.
239
240
```java { .api }
241
public ConfigObject root();
242
public ConfigOrigin origin();
243
public Set<Map.Entry<String, ConfigValue>> entrySet();
244
```
245
246
**Usage Examples:**
247
248
```java
249
// Get root object
250
ConfigObject root = config.root();
251
252
// Get all entries as path-value pairs
253
Set<Map.Entry<String, ConfigValue>> entries = config.entrySet();
254
for (Map.Entry<String, ConfigValue> entry : entries) {
255
String path = entry.getKey();
256
ConfigValue value = entry.getValue();
257
System.out.println(path + " = " + value.render());
258
}
259
260
// Get origin information
261
ConfigOrigin origin = config.origin();
262
String description = origin.description();
263
String filename = origin.filename();
264
int lineNumber = origin.lineNumber();
265
```
266
267
## Configuration Manipulation
268
269
### Path-Based Manipulation
270
271
Create new Config instances with modified paths.
272
273
```java { .api }
274
public Config withOnlyPath(String path);
275
public Config withoutPath(String path);
276
public Config withValue(String path, ConfigValue value);
277
public Config atPath(String path);
278
public Config atKey(String key);
279
```
280
281
**Usage Examples:**
282
283
```java
284
// Extract subset of configuration
285
Config dbConfig = config.withOnlyPath("database");
286
287
// Remove specific path
288
Config withoutDebug = config.withoutPath("debug");
289
290
// Add/update value
291
Config updated = config.withValue("server.port", ConfigValueFactory.fromAnyRef(9090));
292
293
// Wrap config at path
294
Config wrapped = config.atPath("application");
295
296
// Wrap config at key
297
Config keyWrapped = config.atKey("myapp");
298
```
299
300
### Merging and Fallbacks
301
302
Combine configurations with fallback semantics.
303
304
```java { .api }
305
public Config withFallback(ConfigMergeable other);
306
```
307
308
**Usage Examples:**
309
310
```java
311
// Merge with fallback (current config takes precedence)
312
Config defaults = ConfigFactory.parseResources("defaults.conf");
313
Config merged = config.withFallback(defaults);
314
315
// Chain multiple fallbacks
316
Config complete = config
317
.withFallback(ConfigFactory.parseResources("reference.conf"))
318
.withFallback(ConfigFactory.systemProperties())
319
.withFallback(ConfigFactory.systemEnvironment());
320
```
321
322
## Error Handling
323
324
Configuration access methods throw specific exceptions for different error conditions:
325
326
### ConfigException.Missing
327
328
Thrown when a required path is not found.
329
330
```java
331
try {
332
String value = config.getString("missing.path");
333
} catch (ConfigException.Missing e) {
334
// Handle missing configuration
335
String path = e.path(); // Get the missing path
336
}
337
```
338
339
### ConfigException.Null
340
341
Thrown when a path exists but has a null value (extends ConfigException.Missing).
342
343
```java
344
try {
345
String value = config.getString("nullable.path");
346
} catch (ConfigException.Null e) {
347
// Handle null value
348
} catch (ConfigException.Missing e) {
349
// Handle missing path
350
}
351
```
352
353
### ConfigException.WrongType
354
355
Thrown when requesting a value with incompatible type.
356
357
```java
358
try {
359
int value = config.getInt("string.value");
360
} catch (ConfigException.WrongType e) {
361
// Handle type mismatch
362
ConfigValueType actual = e.actual();
363
ConfigValueType expected = e.expected();
364
}
365
```
366
367
## Best Practices
368
369
1. **Use hasPath() for optional values**: Check existence before accessing optional configuration
370
2. **Prefer specific getters**: Use typed getters (getInt, getString) instead of getAnyRef when possible
371
3. **Handle exceptions appropriately**: Distinguish between missing, null, and wrong-type errors
372
4. **Cache expensive operations**: Store Config objects and avoid repeated path lookups
373
5. **Use meaningful path names**: Follow dot-notation conventions (e.g., "database.connection.timeout")
374
6. **Group related settings**: Use nested objects for related configuration (e.g., "server.http.port", "server.https.port")