The PureConfig is a lib for laoding configuraiton files. It can handle many types automatically and support writing configuration.
Quick Start
PureConfig uses Typesafe Config to load configurations. It supports reading file in HOCON (prefered as a superset of the other two formats), JSON, and Java .properties format.
Build import: ivy"com.github.pureconfig::pureconfig:0.12.3"
A sample code:
|
|
Loading a Config
The ConfigSources.default loads a config from application.conf. Other sources include ConfigSource.file, ConfigSource.resources, ConfigSource.url, and ConfigSource.string.
Each source has several loading methods:
load[A]: returns anEither[ConfigReaderFailures, A]loadOrThrow[A]: returns anAor throws an exception.config(): reads as a raw config.cursor(): reads as aConfigCursorwithFallBack(defaultSource).load[A]: load with a default source.optional.withFallback(defaultSource): produce an empty config if a source is missing.recoverWith { case ...}.load[A]: use an alternative soruce if the primary can’t be read.at("my-path").load[A]: to load a specific path in the configuration file.
Supporting Types
Most standard Scala and Java type. Additionally, PureConfig also hands the following collections and composite Scala structure: Option, TraversableOnce collections, Map from String key or types convertible to String (must be configured first), shapeless.HList, case class, class with only public val and var parameters in construtor, sealed case classes (ADTs).
To support a new type T, there should be an implicit instance of ConfigReader[T]. There are three ways to build such an instance for a new type:
|
|
For some types, PureConfig cannot automatically derive a reader because there are multiple ways to convert a configuration value to them. For those types, use methods in pureconfig.configurable. For example, localDataConfigConvert for Java’s LocalDate and genericMapReader[A, B] for a map.
Error Handling
Most load methods return an ConfigReader.Rsult[A], an alias for Either[ConfigReaderFailures, A]. There are several types of ConfigRaderFailure, one is ConvertFailure that has a reason FailureReason, an optional location in the config file and a path in the config. The FailureReason could be ConnotConvert, KeyNotFound, or WrongType.