Permalink
Browse files

Show how to create a Settings class to encapsulate your Config

  • Loading branch information...
1 parent 85a4eda commit 0adc9152d157f1bc1f3028dc38a4327afe1ba89d @havocp havocp committed Apr 13, 2012
Showing with 58 additions and 0 deletions.
  1. +24 −0 README.md
  2. +34 −0 examples/simple-lib/src/main/scala/simplelib/SimpleLib.scala
View
@@ -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
@@ -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)
+ }
+}

0 comments on commit 0adc915

Please sign in to comment.