0
# Configuration Management
1
2
YAML-based configuration system with environment variable substitution, validation, and type-safe access to application settings.
3
4
## Capabilities
5
6
### Configuration Factory
7
8
Factory class for parsing and validating configuration files with support for various formats and sources.
9
10
```java { .api }
11
package io.dropwizard.configuration;
12
13
public class ConfigurationFactory<T> {
14
/**
15
* Builds a configuration object from the given source.
16
*/
17
public T build(ConfigurationSourceProvider provider, String path)
18
throws IOException, ConfigurationException;
19
20
/**
21
* Builds a configuration object from a file.
22
*/
23
public T build(File file) throws IOException, ConfigurationException;
24
25
/**
26
* Builds a configuration object from an input stream.
27
*/
28
public T build(InputStream input) throws IOException, ConfigurationException;
29
30
/**
31
* Creates a new configuration factory.
32
*/
33
public static <T> ConfigurationFactory<T> forClass(Class<T> klass,
34
Validator validator,
35
ObjectMapper objectMapper,
36
String propertyPrefix);
37
}
38
```
39
40
### Configuration Source Providers
41
42
Interfaces for loading configuration from various sources including files, classpath resources, and remote locations.
43
44
```java { .api }
45
package io.dropwizard.configuration;
46
47
public interface ConfigurationSourceProvider {
48
/**
49
* Opens an InputStream for the given path.
50
*/
51
InputStream open(String path) throws IOException;
52
}
53
54
public class FileConfigurationSourceProvider implements ConfigurationSourceProvider {
55
@Override
56
public InputStream open(String path) throws IOException;
57
}
58
59
public class ResourceConfigurationSourceProvider implements ConfigurationSourceProvider {
60
@Override
61
public InputStream open(String path) throws IOException;
62
}
63
64
public class UrlConfigurationSourceProvider implements ConfigurationSourceProvider {
65
@Override
66
public InputStream open(String path) throws IOException;
67
}
68
```
69
70
**Usage Example:**
71
72
```java
73
@Override
74
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
75
// Load configuration from classpath
76
bootstrap.setConfigurationSourceProvider(new ResourceConfigurationSourceProvider());
77
78
// Load configuration from URLs
79
bootstrap.setConfigurationSourceProvider(new UrlConfigurationSourceProvider());
80
}
81
```
82
83
### Environment Variable Substitution
84
85
Support for substituting environment variables and system properties in configuration files.
86
87
```java { .api }
88
package io.dropwizard.configuration;
89
90
public class SubstitutingSourceProvider implements ConfigurationSourceProvider {
91
/**
92
* Creates a substituting source provider with the given underlying provider and substitutor.
93
*/
94
public SubstitutingSourceProvider(ConfigurationSourceProvider provider,
95
StringSubstitutor substitutor);
96
}
97
98
public class EnvironmentVariableSubstitutor extends StringSubstitutor {
99
/**
100
* Creates a substitutor that replaces environment variables.
101
* @param strict if true, throws exception for undefined variables
102
*/
103
public EnvironmentVariableSubstitutor(boolean strict);
104
}
105
```
106
107
**Usage Example:**
108
109
```java
110
@Override
111
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
112
// Enable environment variable substitution
113
bootstrap.setConfigurationSourceProvider(
114
new SubstitutingSourceProvider(
115
bootstrap.getConfigurationSourceProvider(),
116
new EnvironmentVariableSubstitutor(false)
117
)
118
);
119
}
120
```
121
122
**Configuration file with environment variables:**
123
124
```yaml
125
# config.yml
126
database:
127
url: ${DATABASE_URL:-jdbc:h2:mem:test}
128
username: ${DB_USERNAME:-sa}
129
password: ${DB_PASSWORD:-}
130
131
server:
132
applicationConnectors:
133
- type: http
134
port: ${PORT:-8080}
135
```
136
137
### Configuration Validation
138
139
Built-in validation annotations for ensuring configuration correctness at application startup.
140
141
```java { .api }
142
// Standard Bean Validation annotations
143
@NotNull @NotEmpty @Valid @Min @Max @Range @Size @Pattern @Email
144
145
// Dropwizard-specific validation annotations
146
@DurationRange(min = 1, minUnit = TimeUnit.SECONDS, max = 1, maxUnit = TimeUnit.HOURS)
147
@MinDuration(value = 1, unit = TimeUnit.SECONDS)
148
@MaxDuration(value = 1, unit = TimeUnit.HOURS)
149
150
@DataSizeRange(min = 1, minUnit = DataSize.Unit.KILOBYTES, max = 1, maxUnit = DataSize.Unit.MEGABYTES)
151
@MinDataSize(value = 1, unit = DataSize.Unit.KILOBYTES)
152
@MaxDataSize(value = 1, unit = DataSize.Unit.MEGABYTES)
153
154
@OneOf({"value1", "value2", "value3"})
155
@PortRange(min = 1024, max = 65535)
156
157
@ValidationMethod(message = "Custom validation failed")
158
```
159
160
**Usage Example:**
161
162
```java
163
public class DatabaseConfiguration {
164
@NotEmpty
165
@Pattern(regexp = "jdbc:.*")
166
private String url;
167
168
@NotEmpty
169
private String username;
170
171
private String password = "";
172
173
@Min(1) @Max(100)
174
private int maxConnections = 10;
175
176
@DurationRange(min = 1, minUnit = TimeUnit.SECONDS, max = 30, maxUnit = TimeUnit.SECONDS)
177
private Duration connectionTimeout = Duration.seconds(5);
178
179
@DataSizeRange(min = 1, minUnit = DataSize.Unit.KILOBYTES)
180
private DataSize maxQuerySize = DataSize.megabytes(1);
181
182
@ValidationMethod(message = "Password cannot be empty when username is provided")
183
public boolean isPasswordValid() {
184
return username.isEmpty() || !password.isEmpty();
185
}
186
187
// getters and setters with @JsonProperty
188
}
189
```
190
191
### Custom Configuration Classes
192
193
Patterns for creating type-safe configuration classes that extend the base Configuration class.
194
195
```java { .api }
196
public class MyConfiguration extends Configuration {
197
@Valid
198
@NotNull
199
private DatabaseConfiguration database = new DatabaseConfiguration();
200
201
@Valid
202
@NotNull
203
private RedisConfiguration redis = new RedisConfiguration();
204
205
@NotEmpty
206
private String applicationName = "my-service";
207
208
@OneOf({"development", "staging", "production"})
209
private String environment = "development";
210
211
@JsonProperty("database")
212
public DatabaseConfiguration getDatabase() { return database; }
213
214
@JsonProperty("database")
215
public void setDatabase(DatabaseConfiguration database) { this.database = database; }
216
217
// Additional getters and setters
218
}
219
```
220
221
### Configuration Serialization
222
223
Jackson annotations for controlling JSON/YAML serialization and deserialization of configuration objects.
224
225
```java { .api }
226
// Property mapping
227
@JsonProperty("property_name")
228
@JsonAlias({"alias1", "alias2"})
229
230
// Inclusion/exclusion
231
@JsonIgnore
232
@JsonIgnoreProperties({"property1", "property2"})
233
@JsonIgnoreProperties(ignoreUnknown = true)
234
235
// Default values
236
@JsonProperty(defaultValue = "default_value")
237
238
// Custom serialization
239
@JsonSerialize(using = CustomSerializer.class)
240
@JsonDeserialize(using = CustomDeserializer.class)
241
242
// Property ordering
243
@JsonPropertyOrder({"prop1", "prop2", "prop3"})
244
```
245
246
**Usage Example:**
247
248
```java
249
@JsonIgnoreProperties(ignoreUnknown = true)
250
@JsonPropertyOrder({"name", "version", "environment"})
251
public class AppConfiguration {
252
@JsonProperty("app_name")
253
private String name;
254
255
@JsonProperty(defaultValue = "1.0.0")
256
private String version;
257
258
@JsonIgnore
259
private String internalProperty;
260
261
@JsonSerialize(using = ToStringSerializer.class)
262
@JsonDeserialize(using = DurationDeserializer.class)
263
private Duration timeout;
264
}
265
```
266
267
## Configuration File Formats
268
269
### YAML Configuration
270
271
Primary configuration format with support for complex nested structures, lists, and environment variable substitution.
272
273
```yaml
274
# Example configuration file
275
applicationName: "My Service"
276
environment: ${ENVIRONMENT:-development}
277
278
server:
279
applicationConnectors:
280
- type: http
281
port: ${PORT:-8080}
282
adminConnectors:
283
- type: http
284
port: ${ADMIN_PORT:-8081}
285
286
database:
287
driverClass: org.postgresql.Driver
288
url: ${DATABASE_URL}
289
username: ${DB_USERNAME}
290
password: ${DB_PASSWORD}
291
maxWaitForConnection: 1s
292
validationQuery: "SELECT 1"
293
properties:
294
hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect
295
296
logging:
297
level: INFO
298
loggers:
299
com.example: DEBUG
300
appenders:
301
- type: console
302
- type: file
303
currentLogFilename: ./logs/application.log
304
archivedLogFilenamePattern: ./logs/application-%d.log.gz
305
archivedFileCount: 5
306
```
307
308
### JSON Configuration
309
310
Alternative JSON format support for configuration files.
311
312
```json
313
{
314
"applicationName": "My Service",
315
"server": {
316
"applicationConnectors": [{
317
"type": "http",
318
"port": 8080
319
}]
320
},
321
"database": {
322
"url": "jdbc:postgresql://localhost/mydb",
323
"username": "user",
324
"password": "pass"
325
}
326
}
327
```