HOCON Configuration Management with Kora¶
This guide introduces type-safe configuration with Kora and HOCON. It covers how configuration values are mapped from application.conf into typed interfaces, how required and optional values are
represented in Java and Kotlin code, and how one reusable config shape can be bound to several sections without duplicating the whole block. You will also see how environment variables and printed
runtime output make resolved configuration easy to inspect.
If you want to check your progress along the way, use the finished working example: Kora Java Config HOCON App.
If you want to check your progress along the way, use the finished working example: Kora Kotlin Config HOCON App.
What You'll Build¶
You'll build a small runnable Kora application that:
- binds
app.name,app.version, andapp.environmentthrough@ConfigSource - treats
APP_VERSIONas required andAPP_NAMEas an optional override - defines one reusable
LibConfigwithendpointandrequestTimeout - maps that same
LibConfigforlib1andlib2 - reuses one shared HOCON object and overrides only one field for the second library
- prints all resolved values to
stdoutduring startup
What You'll Need¶
- JDK 25 or later
- Gradle 9+
- A text editor or IDE
- Completed Creating Your First Kora App guide
Kora 2.0 artifacts are compiled for Java 25, so the JDK that compiles the application must be 25 or newer.
Prerequisites¶
Required: Complete Getting Started
This guide assumes you have completed Creating Your First Kora App and already have a runnable Kora project with the application plugin and a generated application graph.
If you haven't created that baseline yet, complete the getting started guide first, because this guide focuses on typed configuration rather than initial project setup.
Overview¶
Configuration is how runtime environments influence application behavior without changing code. Ports, credentials, feature switches, timeouts, and external service addresses should live outside compiled classes, but application code still needs a type-safe way to read them.
The main lesson is that configuration should be explicit at the application boundary. Components should not search environment variables or parse files by themselves; they should receive typed configuration from the graph.
HOCON and Type-Safe Mapping¶
Kora can read HOCON configuration and map it into Java or Kotlin interfaces. Instead of passing raw strings and maps through the application, components receive typed configuration objects. This makes required values explicit and lets the compiler help with configuration usage.
This guide uses two complementary mapping styles:
@ConfigSource("app")maps one fixed config section to a type-safe dependency@ConfigMappermaps a reusable config shape that can be bound to different paths
Use @ConfigSource when a component needs one stable section of application configuration. Use @ConfigMapper when the same structure appears in several places and you want one reusable
mapping rule whose path is chosen in a module factory.
Both annotations generate a ConfigValueMapper<T> implementation at compile time. The difference is only who picks the path: @ConfigSource bakes it into a generated module, while @ConfigMapper
leaves it to you.
Required and Optional Values¶
HOCON supports useful composition features:
- required environment substitution such as
${APP_VERSION} - optional environment substitution such as
${?APP_NAME} - object reuse such as
${common-lib}
These features let one configuration file stay readable while still adapting to local development, tests, and deployed environments.
On the code side the rule is just as short: every method of a config interface is a required value unless you mark it nullable or give it a default implementation. Like the protobuf contract in gRPC
or the cache contract in caching, a config type is a boundary contract. It says which runtime values the application expects and what shape those values must have.
Configuration as a Graph Dependency¶
In Kora, configuration is part of the dependency graph. A component can request a typed config object in its constructor just like it requests a repository or client. That makes configuration dependencies visible and testable. It also keeps configuration parsing at the boundary of the graph instead of scattered across application code.
The practical flow is:
- add the HOCON configuration module
- define a fixed application config source
- bind required and optional values
- define a reusable config mapper
- reuse one config shape for multiple library settings
- run the app and inspect resolved configuration
Dependencies¶
Add the HOCON module to your existing project and keep logging enabled so startup behavior is visible while you learn.
Update build.gradle:
Why this matters:
config-hoconenables HOCON file loading in the application graphlogging-logbackkeeps startup and troubleshooting visible while the app runs
Versions come from the io.koraframework:kora-bom platform the project already imports, so no explicit version is needed here.
Modules¶
Start with the smallest possible application graph that can load HOCON config and run a Kora application.
At this point we are not adding application-specific configuration yet. We are only preparing the graph so later steps can bind typed config and print resolved values.
Create src/main/java/io/koraframework/guide/config/hocon/Application.java:
package io.koraframework.guide.config.hocon;
import io.koraframework.application.graph.KoraApplication;
import io.koraframework.common.annotation.KoraApp;
import io.koraframework.config.hocon.HoconConfigModule;
import io.koraframework.logging.logback.LogbackModule;
@KoraApp
public interface Application extends
HoconConfigModule, // <----- Connected module
LogbackModule {
static void main(String[] args) {
KoraApplication.run(ApplicationGraph::graph);
}
}
Create src/main/kotlin/io/koraframework/guide/config/hocon/Application.kt:
package io.koraframework.guide.config.hocon
import io.koraframework.application.graph.KoraApplication
import io.koraframework.common.annotation.KoraApp
import io.koraframework.config.hocon.HoconConfigModule
import io.koraframework.logging.logback.LogbackModule
@KoraApp
interface Application :
HoconConfigModule, // <----- Connected module
LogbackModule
fun main() {
KoraApplication.run(ApplicationGraph::graph)
}
Why this matters:
HoconConfigModuleactivates HOCON-based configuration loadingLogbackModuleadds basic startup and troubleshooting logs- the graph stays minimal for now: it can start the application and read the config file
HoconConfigModule also decides which file to read. With no system property set it looks for application.conf on the classpath; config.resource and config.file override that, and we use the
first of them at the end of this guide.
Typed sections are introduced gradually: first the application section, then a reusable library shape, and only after that the explicit mapping from libs.lib1 and libs.lib2 to two instances of the same type.
If you want more background on graph wiring and factories, see the Container documentation.
Application Configuration¶
Now introduce the first typed config contract: a stable application section named app.
This is the simplest and most common config pattern in Kora. Instead of reading keys manually, you declare the shape once and inject it wherever it is needed.
Create src/main/java/io/koraframework/guide/config/hocon/AppConfig.java:
Why this matters:
@ConfigSource("app")makes theappsection a first-class dependency- the contract stays close to the code that consumes it
- refactoring config keys becomes safer because the structure is explicit in one place
All three methods return non-nullable types, so all three values are required. Making one of them optional is a code change, not a file change: mark it @Nullable in Java or return a nullable type in
Kotlin. Method names are matched leniently, so someBarString() also reads some-bar-string and some_bar_string from the file.
Required Values¶
With AppConfig defined, we can now decide which values are mandatory and which can fall back to defaults.
Update src/main/resources/application.conf:
app {
name = "Task Management App"
name = ${?APP_NAME}
version = ${APP_VERSION}
environment = "development"
}
What this means:
version = ${APP_VERSION}is required, so startup fails ifAPP_VERSIONis missingname = ${?APP_NAME}is optional and only overrides the default when the variable existsenvironmentstays a normal static value because this guide does not need to vary it yet
This is an important HOCON pattern: make critical values fail fast, but keep cosmetic or environment-specific overrides optional.
Note that the two name lines are not a mistake. HOCON keeps the last assignment for a key, and ${?APP_NAME} contributes nothing when the variable is unset, so the literal above it survives. This is
how a default plus an optional override is spelled in HOCON.
For more on substitution rules and supported value types, see the Configuration documentation.
Library Configuration¶
Next, create a reusable config shape for one library.
Imagine that an abstract library needs two settings:
endpointrequestTimeout
Instead of keeping those as raw keys, define them once as a type.
Create src/main/java/io/koraframework/guide/config/hocon/LibConfig.java:
Now that LibConfig exists, return to the application graph and show explicitly where the two library configs come from.
@ConfigMapper generates a ConfigValueMapper<LibConfig> for the shape but binds no path, and the graph methods choose concrete branches of the config file. This gives Kora two different instances of the same type: one for libs.lib1 and one for libs.lib2.
Update src/main/java/io/koraframework/guide/config/hocon/Application.java:
package io.koraframework.guide.config.hocon;
import io.koraframework.application.graph.KoraApplication;
import io.koraframework.common.annotation.KoraApp;
import io.koraframework.common.annotation.Tag;
import io.koraframework.config.common.Config;
import io.koraframework.config.common.mapper.ConfigValueMapper;
import io.koraframework.config.hocon.HoconConfigModule;
import io.koraframework.logging.logback.LogbackModule;
@KoraApp
public interface Application extends
HoconConfigModule, // <----- Connected module
LogbackModule {
final class Lib1Tag {}
final class Lib2Tag {}
@Tag(Lib1Tag.class)
default LibConfig lib1Config(Config config, ConfigValueMapper<LibConfig> mapper) {
return mapper.mapOrThrow(config.get("libs.lib1"));
}
@Tag(Lib2Tag.class)
default LibConfig lib2Config(Config config, ConfigValueMapper<LibConfig> mapper) {
return mapper.mapOrThrow(config.get("libs.lib2"));
}
static void main(String[] args) {
KoraApplication.run(ApplicationGraph::graph);
}
}
Update src/main/kotlin/io/koraframework/guide/config/hocon/Application.kt:
package io.koraframework.guide.config.hocon
import io.koraframework.application.graph.KoraApplication
import io.koraframework.common.annotation.KoraApp
import io.koraframework.common.annotation.Tag
import io.koraframework.config.common.Config
import io.koraframework.config.common.mapper.ConfigValueMapper
import io.koraframework.config.hocon.HoconConfigModule
import io.koraframework.logging.logback.LogbackModule
@KoraApp
interface Application :
HoconConfigModule, // <----- Connected module
LogbackModule {
class Lib1Tag private constructor()
class Lib2Tag private constructor()
@Tag(Lib1Tag::class)
fun lib1Config(config: Config, mapper: ConfigValueMapper<LibConfig>): LibConfig {
return mapper.mapOrThrow(config.get("libs.lib1"))
}
@Tag(Lib2Tag::class)
fun lib2Config(config: Config, mapper: ConfigValueMapper<LibConfig>): LibConfig {
return mapper.mapOrThrow(config.get("libs.lib2"))
}
}
fun main() {
KoraApplication.run(ApplicationGraph::graph)
}
What happens here:
Lib1TagandLib2Tagdistinguish twoLibConfiginstances in the graphconfig.get("libs.lib1")andconfig.get("libs.lib2")select different config branchesConfigValueMapper<LibConfig>converts each branch into a typed object
ConfigValueMapper<T> offers two reading methods. map(...) may return null, while mapOrThrow(...) turns that null into a ConfigValueException. Factory methods normally use mapOrThrow(...),
because a missing library section is a startup error rather than a valid state.
Both factories are now part of the graph, so both sections have to exist. Add them to application.conf:
app {
name = "Task Management App"
name = ${?APP_NAME}
version = ${APP_VERSION}
environment = "development"
}
libs {
lib1 {
endpoint = "https://integration.local/api"
requestTimeout = 5s
}
lib2 {
endpoint = "https://integration-2.local/api"
requestTimeout = 5s
}
}
At this stage the application starts, and Kora converts 5s directly into Duration. But the two sections are almost identical, and that duplication is what the next step removes.
Configuration file¶
Both libraries need exactly the same shape, and right now the shared values are copied twice.
HOCON gives you a better option: place the shared values in one object and reuse that object where needed.
Update application.conf again:
app {
name = "Task Management App"
name = ${?APP_NAME}
version = ${APP_VERSION}
environment = "development"
}
common-lib = {
endpoint = "https://integration.local/api"
requestTimeout = 5s
}
libs.lib1 = ${common-lib}
libs.lib2 = ${common-lib}
libs.lib2.endpoint = "https://integration-2.local/api"
What changed:
common-libnow stores the shared defaults oncelibs.lib1reuses the whole objectlibs.lib2also reuses the whole objectlibs.lib2.endpointoverrides only one field after reuse
Order matters in the last three lines: libs.lib2.endpoint has to come after libs.lib2 = ${common-lib}, otherwise the whole-object assignment would replace it.
This is the payoff of combining HOCON reuse with @ConfigMapper: one config shape, multiple mapped instances, minimal duplication.
Resolved Values¶
The last step is to prove that everything was injected correctly.
Instead of adding an HTTP endpoint, this guide uses a small @Root component that prints all resolved values to standard output during startup. This mirrors the console-style validation used in the
dependency injection guide.
Create src/main/java/io/koraframework/guide/config/hocon/ConfigRunner.java:
package io.koraframework.guide.config.hocon;
import java.util.LinkedHashMap;
import java.util.Map;
import io.koraframework.application.graph.Lifecycle;
import io.koraframework.common.annotation.Component;
import io.koraframework.common.annotation.Root;
import io.koraframework.common.annotation.Tag;
@Root
@Component
public final class ConfigRunner implements Lifecycle {
private final AppConfig appConfig;
private final LibConfig lib1Config;
private final LibConfig lib2Config;
public ConfigRunner(
AppConfig appConfig,
@Tag(Application.Lib1Tag.class) LibConfig lib1Config,
@Tag(Application.Lib2Tag.class) LibConfig lib2Config
) {
this.appConfig = appConfig;
this.lib1Config = lib1Config;
this.lib2Config = lib2Config;
}
public Map<String, String> snapshot() {
Map<String, String> values = new LinkedHashMap<>();
values.put("name", this.appConfig.name());
values.put("version", this.appConfig.version());
values.put("environment", this.appConfig.environment());
values.put("lib1.endpoint", this.lib1Config.endpoint());
values.put("lib1.requestTimeout", this.lib1Config.requestTimeout().toString());
values.put("lib2.endpoint", this.lib2Config.endpoint());
values.put("lib2.requestTimeout", this.lib2Config.requestTimeout().toString());
return values;
}
@Override
public void init() {
System.out.println("Config guide start");
this.snapshot().forEach((key, value) -> System.out.println(key + "=" + value));
}
@Override
public void release() {
System.out.println("Application shutdown");
}
}
Create src/main/kotlin/io/koraframework/guide/config/hocon/ConfigRunner.kt:
package io.koraframework.guide.config.hocon
import io.koraframework.application.graph.Lifecycle
import io.koraframework.common.annotation.Component
import io.koraframework.common.annotation.Root
import io.koraframework.common.annotation.Tag
@Root
@Component
class ConfigRunner(
private val appConfig: AppConfig,
@Tag(Application.Lib1Tag::class) private val lib1Config: LibConfig,
@Tag(Application.Lib2Tag::class) private val lib2Config: LibConfig,
) : Lifecycle {
fun snapshot(): Map<String, String> {
return linkedMapOf(
"name" to appConfig.name(),
"version" to appConfig.version(),
"environment" to appConfig.environment(),
"lib1.endpoint" to lib1Config.endpoint(),
"lib1.requestTimeout" to lib1Config.requestTimeout().toString(),
"lib2.endpoint" to lib2Config.endpoint(),
"lib2.requestTimeout" to lib2Config.requestTimeout().toString(),
)
}
override fun init() {
println("Config guide start")
snapshot().forEach { (key, value) -> println("$key=$value") }
}
override fun release() {
println("Application shutdown")
}
}
Why this matters:
@Rootensures the runner is actually created when the application startsLifecyclegives you a natural place to print or validate injected valuessnapshot()keeps the runtime output and the tests aligned around one contract
The same @Tag markers that disambiguated the two factories now select which LibConfig each constructor parameter receives. Without them the graph could not tell the two components apart.
Generated Configuration Code¶
Like the rest of Kora, configuration mapping is generated at compile time. After ./gradlew clean classes, look at what the processor produced:
guides/java/kora-java-guide-config-hocon-app/build/generated/sources/annotationProcessor/java/main/io/koraframework/guide/config/hocon/AppConfigModule.java
guides/java/kora-java-guide-config-hocon-app/build/generated/sources/annotationProcessor/java/main/io/koraframework/guide/config/hocon/$AppConfig_ConfigValueMapper.java
guides/java/kora-java-guide-config-hocon-app/build/generated/sources/annotationProcessor/java/main/io/koraframework/guide/config/hocon/$LibConfig_ConfigValueMapper.java
guides/kotlin/kora-kotlin-guide-config-hocon-app/build/generated/ksp/main/kotlin/io/koraframework/guide/config/hocon/AppConfigModule.kt
guides/kotlin/kora-kotlin-guide-config-hocon-app/build/generated/ksp/main/kotlin/io/koraframework/guide/config/hocon/$AppConfig_ConfigValueMapper.kt
guides/kotlin/kora-kotlin-guide-config-hocon-app/build/generated/ksp/main/kotlin/io/koraframework/guide/config/hocon/$LibConfig_ConfigValueMapper.kt
@ConfigSource produced an entire module, and it looks exactly like the factories you wrote by hand for LibConfig:
That is the whole difference between the two annotations: @ConfigSource writes this module for you at a fixed path, @ConfigMapper does not, which is why you wrote two tagged factories instead.
The mapper itself shows where required values are enforced:
requestTimeout is handled differently: instead of a hand-written branch, the generated mapper takes a ConfigValueMapper<Duration> as a constructor dependency. Every supported value type reaches the
mapper the same way, which is how a custom type can be added later without touching the config interface.
Run Application¶
Use the standard guide flow:
app.version is required, so APP_VERSION must be present before the application starts:
In the runnable Java sample, the run task already injects APP_VERSION from koraVersion in gradle.properties, so a plain ./gradlew run works there out of the box.
If you want to override the application name too, add APP_NAME before startup:
Application Output¶
When the application starts, it prints:
Config guide start
name=Task Management App
version=1.0.0
environment=development
lib1.endpoint=https://integration.local/api
lib1.requestTimeout=PT5S
lib2.endpoint=https://integration-2.local/api
lib2.requestTimeout=PT5S
PT5S is the ISO-8601 form of Duration.ofSeconds(5), which confirms that 5s was mapped to a real Duration and not to a string. If you provide APP_NAME, the printed name= line reflects the
override:
Prod configuration¶
A common next step is to keep separate config files for different environments such as development, staging, or production.
For example, create src/main/resources/application-prod.conf:
This file reuses the base configuration from application.conf through the HOCON include directive and overrides only the values that differ for production. Included files take part in the same
merge and substitution resolution as the main file, so ${APP_VERSION} still works.
Select the alternative file with the config.resource system property. The Gradle application plugin does not forward -D flags from the command line to the application process, so declare it on
the run task:
A built distribution takes the same property through JAVA_OPTS:
With that override in place, the startup output prints:
Use config.file instead of config.resource to read a file from disk rather than from the classpath. Only one of the two may be set: if both are, the application fails at startup with
Application config source is ambiguous.
For more on file resolution and external config files, see the Configuration documentation.
Best Practices¶
- Use
@ConfigSourcefor stable application-level config that belongs to one well-known section. - Use
@ConfigMapperwhen the same config shape is reused under multiple paths, and pick the path in a module factory. - Prefer
mapOrThrow(...)overmap(...)in factories, so a missing section fails at startup instead of producingnull. - Keep required values explicit with
${VAR_NAME}and optional overrides explicit with${?VAR_NAME}. - Prefer object reuse plus small field overrides over copying large config blocks.
- Keep startup diagnostics simple while exploring configuration behavior;
System.out.println(...)is enough for learning flows.
Summary¶
You now have a working HOCON-based Kora application that binds configuration in two ways. AppConfig maps a stable app section, while LibConfig is mapped twice from two different paths with
different tags. HOCON reuse keeps the file compact, and one override changes only the second library endpoint.
Key Concepts¶
@ConfigSource:
- maps one fixed config section to a type-safe interface
- generates a module that calls
mapOrThrow(config.get("app"))for you - works well for application settings like
app.nameandapp.environment
Required vs Optional Values:
- every interface method is required unless it is nullable or has a
defaultimplementation ${APP_VERSION}is required and fails fast when missing${?APP_NAME}is optional and overrides the default only when present
@ConfigMapper and Reuse:
- generates a
ConfigValueMapper<T>without binding a path - one config shape can be mapped from multiple paths, disambiguated with
@Tag ${common-lib}copies the full object into another path- a later assignment such as
libs.lib2.endpoint = ...overrides only one field
Troubleshooting¶
Application fails at startup with an unresolved substitution:
app.version = ${APP_VERSION} is mandatory. In the runnable Java sample, run provides it automatically from koraVersion. Otherwise you must set APP_VERSION before startup.
Startup fails with Config expected value, but got null at path: '...':
A required value is missing from the resulting configuration. Either add the key to the file, or make the method optional with @Nullable in Java or a nullable return type in Kotlin, or give it a
default implementation.
APP_NAME does not override the default name:
HOCON keeps the last assignment, so the optional override must come after the default:
Library config values are duplicated across sections:
Move the shared values into one object such as common-lib and reuse it through ${common-lib} instead of copying the full block into both libraries.
Application config source is ambiguous:
Both config.resource and config.file are set. Remove one of the two system properties.
Build hangs or fails unexpectedly:
Stop Gradle daemons and retry:
AccessDeniedException in the Gradle cache on Windows:
If cached files are locked by another process, retry with a fresh session cache:
What's Next?¶
- YAML Configuration to see the same typed configuration model with a different file format.
- JSON Processing to make request and response DTOs explicit in the small application you already have.
- Build an HTTP Server after JSON, because that guide builds on JSON DTO mapping and turns the app into a fuller HTTP API.
- Learn Dependency Injection Basics if the generated graph and config factories still feel unclear.
Help¶
If you encounter issues:
- compare with Kora Java Config HOCON App and Kora Kotlin Config HOCON App
- check the Configuration documentation
- check the Container documentation
- check the HOCON config example
- read the HOCON specification