Skip to main content

Ocular

Ocular manages configuration files for you. It is a small wrapper around Jackson 3. You write plain Java classes, and Ocular reads them from files, creates missing files with default values and saves them again.

What you get:

  • one place for all configuration files of your application,
  • JSON, YAML and TOML out of the box, picked by the file ending,
  • default files created on first start,
  • broken files backed up and replaced, or kept untouched if you prefer,
  • values overridden by environment variables and system properties,
  • full access to the Jackson mapper when you need it.

Requirements​

WhatVersion
Java21 or newer. Ocular is compiled for Java 21.
Jackson3 (tools.jackson). Ocular brings jackson-databind with it.
SLF4JOcular logs through slf4j-api and brings it. Add an SLF4J binding (for example slf4j-simple or Logback) to see the log output.

Add the dependency​

Ocular is published to Maven Central. It is also mirrored on EldoNexus (https://eldonexus.de/repository/maven-public/).

repositories {
mavenCentral()
}

dependencies {
implementation("dev.chojo:ocular:2.3.2")
}

YAML and TOML​

JSON works right away. For YAML or TOML you add the Jackson module for that format yourself. Ocular only compiles against them and does not ship them. Keep all Jackson parts on the same version, for example with the Jackson BOM.

dependencies {
implementation(platform("tools.jackson:jackson-bom:3.1.1"))
implementation("tools.jackson.dataformat:jackson-dataformat-yaml")
implementation("tools.jackson.dataformat:jackson-dataformat-toml")
}

Only add the formats you use. The module has to be there at runtime too, not only at compile time.

A first look​

A configuration is a plain class with fields and default values:

public class AppConfig {
private String host = "localhost";
private int port = 8080;

public String host() {
return host;
}

public int port() {
return port;
}
}

Describe the file with a Key and build a Configurations instance:

Key<AppConfig> key = Key.builder(Path.of("config.yml"), AppConfig::new).build();

Configurations<AppConfig> configurations = Configurations.builder(key, new YamlDataFormat())
.setBase(Path.of("config"))
.build();

AppConfig config = configurations.main();

On the first call, Ocular writes config/config.yml with the default values:

host: "localhost"
port: 8080

On later starts it reads the file instead.

Where to go next​