Skip to content

Module hexagon_settings

Module hexagon_settings

This module holds utilities to handle applications' configuration parameters.

Install the Dependency

1
2
3
4
5
repositories {
    mavenCentral()
}

implementation("com.hexagonkt:hexagon_settings:$hexagonVersion")
1
2
3
4
5
<dependency>
  <groupId>com.hexagonkt</groupId>
  <artifactId>hexagon_settings</artifactId>
  <version>$hexagonVersion</version>
</dependency>

Settings

This module helps loading external settings from different sources. You can change the settings sources, the default ones are (bottom sources override top ones):

  1. Resource /application.json.
  2. Resource /application.yml.
  3. Environment variables starting with APPLICATION_.
  4. System properties starting with service.
  5. File ./application.json from the application run directory.
  6. File ./application.yml from the application run directory.
  7. Resource /application_test.json.
  8. Resource /application_test.yml.

Configuration parameters are loaded from the defined sources into a map. Latter sources override previous parameters with the same name if they exist.

Tip

The map with configuration parameters can be converted to any type using the toObject utility method in Core serialization helpers.

Below there is a code fragment showing how to add custom settings sources and load its properties:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
data class Configuration(
    val stringProperty: String,
    val integerProperty: Int,
    val booleanProperty: Boolean,
)

SettingsManager.settings = Settings(
    ObjectSource(
        "stringProperty" to "str",
        "integerProperty" to 101,
        "booleanProperty" to true
    )
)

val configuration = SettingsManager.settings.parameters.toObject<Configuration>()
assert(configuration.stringProperty == "str")
assert(configuration.integerProperty == 101)
assert(configuration.booleanProperty)

For defining simple settings, data classes can be used instead this module:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
data class Configuration(
    val port: Int = System.getenv("NOT_FOUND_PORT")?.toInt() ?: 1415,
    val url: String = System.getProperty("testUrl") ?: "http://example.org",
)

val productionConfiguration: Configuration = Configuration()

assertEquals(1415, productionConfiguration.port)
assertEquals("http://example.org", productionConfiguration.url)

// For tests, values can be changed using environment variables or system properties
System.setProperty("testUrl", "http://test.example.org")
val testConfiguration: Configuration = Configuration()

assertEquals(1415, testConfiguration.port)
assertEquals("http://test.example.org", testConfiguration.url)

Package com.hexagonkt.settings

Load settings from different data sources and formats.