Ratpack 1.1 introduced a feature to use command line arguments for our application configuration. We must use the args
method of the ConfigDataBuilder
class. We can define a common prefix for the arguments and the separator between the configuration property and value. If we don't specify any arguments then Ratpack assumes there is no prefix and the separator is the equal sign (=
).
In the following example Ratpack application we use the args
method and rely on all the default settings:
// File: src/ratpack/Ratpack.groovy import ratpack.config.ConfigData import ratpack.config.ConfigDataBuilder import static groovy.json.JsonOutput.prettyPrint import static groovy.json.JsonOutput.toJson import static ratpack.groovy.Groovy.ratpack class SimpleConfig { String message } ratpack { bindings { final ConfigData configData = ConfigData.of { ConfigDataBuilder builder -> // We use the args method to use // command line arguments to configure // our application. The arguments // must have a key and value separated by // an equal sign (=). // We pass the argument list (args) which is // available in our Ratpack.groovy context. builder.args(args) builder.build() } // Assign all configuration properties from the /simple node // to the properties in the SimpleConfig class. bindInstance(SimpleConfig, configData.get('/simple', SimpleConfig)) } handlers { get('configprops') { SimpleConfig config -> render(prettyPrint(toJson(config))) } } }
If we use Gradle to run our application we can reconfigure the run
task to pass command line arguments:
// File: build.gradle ... run { args 'simple.message=Sample message' } ...
If we run the application with our Gradle build file we can request the configprops
path and get the following result:
$ http localhost:5050/configprops ... { "message": "Sample message" } $
Written with Ratpack 1.1.1.