typesafehub/config — pull request #107 by benmccann (2013-11-18 06:17:26+00:00)
Title: Add a config to java bean converter

The hardest thing to deal with in using config files is that the Config is untyped and takes string arguments for everything. For awhile we had lots of code that looked like config.getString("username") and we were passing these configs around and grabbing properties out by their string names. Then we created Java beans where the property names match the property names in the config file and marshalled the data into them which is much nicer.

When our Play server starts we convert the configs to Java beans:

ElasticSearchConfig elasticSearchConfig = BeanFactory.populateBeanFromConfig(
configuration.getConfig("elasticsearch").asMap(), ElasticSearchConfig.class);

These then are able to be injected into our controllers:

@Inject
public MyController(ElasticSearchConfig elasticSearchConfig) {
elasticSearchConnection = new ElasticSearchConnection(elasticSearchConfig.getHost(), elasticSearchConfig.getPort());
}

This is very nice because we can pass these Java beans all around our code and if we ever change a property name in the config file then we only have to update it one place. It also makes testing much easier as well. I thought this would be a useful piece of functionality to share back with the community.