diff --git a/README.md b/README.md index 9d1b5382..2967a449 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,30 @@ In brief, as shown in the examples: format or data source you like with the methods in `ConfigValueFactory`. +## Schemas and Validation + +There isn't a schema language or anything like that. However, two +suggested tools are: + + - use the + [checkValid() method](http://typesafehub.github.com/config/latest/api/com/typesafe/config/Config.html#checkValid%28com.typesafe.config.Config,%20java.lang.String...%29) + - access your config through a Settings class with a non-lazy + field for each setting, and instantiate it on startup + +In Scala, a Settings class might look like: + + class Settings(config: Config) { + + // validate vs. reference.conf + config.checkValid(ConfigFactory.defaultReference(), "simple-lib") + + // non-lazy fields, we want all exceptions at construct time + val foo = config.getString("simple-lib.foo") + val bar = config.getInt("simple-lib.bar") + } + +See the examples/ directory for a full compilable program. + ## Standard behavior The convenience method `ConfigFactory.load()` loads the following diff --git a/examples/simple-lib/src/main/scala/simplelib/SimpleLib.scala b/examples/simple-lib/src/main/scala/simplelib/SimpleLib.scala index 3e880198..926eed91 100644 --- a/examples/simple-lib/src/main/scala/simplelib/SimpleLib.scala +++ b/examples/simple-lib/src/main/scala/simplelib/SimpleLib.scala @@ -23,3 +23,37 @@ class SimpleLibContext(config: Config) { println("The setting '" + path + "' is: " + config.getString(path)) } } + +// Here is an OPTIONAL alternative way to access settings, which +// has the advantage of validating fields on startup and avoiding +// typos. This is redundant with the SimpleLibContext above, +// in fact we'll show a settings-based context below. +class SimpleLibSettings(config: Config) { + + // checkValid(), just as in the plain SimpleLibContext + config.checkValid(ConfigFactory.defaultReference(), "simple-lib") + + // note that these fields are NOT lazy, because if we're going to + // get any exceptions, we want to get them on startup. + val foo = config.getString("simple-lib.foo") + val hello = config.getString("simple-lib.hello") + val whatever = config.getString("simple-lib.whatever") +} + +// This is a different way to do SimpleLibContext, using the +// SimpleLibSettings class to encapsulate and validate your +// settings on startup +class SimpleLibContext2(config: Config) { + val settings = new SimpleLibSettings(config) + + def this() { + this(ConfigFactory.load()) + } + + // this is the amazing functionality provided by simple-lib with a Settings class + def printSettings() { + println("foo=" + settings.foo) + println("hello=" + settings.hello) + println("whatever=" + settings.whatever) + } +}