Skip to content

API Examples

zleonov edited this page Dec 6, 2023 · 15 revisions

This document is a short introduction into the basic use cases of Optional Config. It assumes basic familiarity with Typesafe Config.

Sample configuration

Consider the following simple configuration that defines properties related to an SQL database. Let's assume it is stored in application.conf on the classpath:

database {
    host = "jdbc:mysql://localhost" // required
    name = mysql                    // required
    port = 3306                     // optional
    username = admin                // required
    password = Password123          // required
    timeout = null                  // optional
}

Getting started

An instance of OptionalConfig can be constructed by passing a Config object to the OptionalConfig.from method:

final Config config = ConfigFactory.load();
final OptionalConfig conf = OptionalConfig.from(config);

Accessing properties

Assuming we have some constant fields for our optional properties:

private static final long CONNECT_TIMEOUT = 60000;
private static final int  DEFAULT_PORT    = 3306;

We can now use the OptionalConfig class created in the last step to query the values for the stored configuration properties:

// Required
final String host     = conf.getString("database.host");
final String database = conf.getString("database.name");
final String username = conf.getString("database.username");
final String password = conf.getString("database.password");

// Optional
final int    port           = conf.getOptionalInteger("database.port").orElse(DEFAULT_PORT);
final long   connectTimeout = conf.getOptionalLong("database.timeout").orElse(CONNECT_TIMEOUT);

Strict mode

Strict mode determines how null values are handled. By default strict mode is set to true which means null values will result in exceptions (except for the explicit getOptional methods). When strict mode is set to false, null values are permissible in both property values and list elements. Since OptionalConfig instances are immutable, calling setStrictMode returns an immutable copy of the current OptionalConfig with the specified strict mode setting.

final OptionalConfig conf = OptionalConfig.from(config).setStrictMode(false);
System.out.println(conf.getString("database.timeout")); // prints null

Refer to the project specifications for more details.