§Java Configuration API Migration
The class play.Configuration
was deprecated in favor of using Typesafe Config directly. So, instead of using play.Configuration
you must now use com.typesafe.config.Config
. For example:
Before:
import play.Configuration;
public class Foo {
private final Configuration configuration;
@javax.inject.Inject
public Foo(Configuration configuration) {
this.configuration = configuration;
}
}
After:
import com.typesafe.config.Config;
public class Foo {
private final Config config;
@javax.inject.Inject
public Foo(Config config) {
this.config = config;
}
}
§Using a reference.conf
file
Of course, there are differences between the Config
and play.Configuration
APIs. The main one is how to handle default values. Typesafe Config advocates that all configuration keys must be declared in your .conf
files, including the default values. Play itself is using reference.conf
files to declare default values for all the possible configurations. To avoid the hassle of handling missing values, you can do the same if you are distributing a library. For your application, you can declare all the values directly inside application.conf
. For example:
Before:
// Here we have the default values inside the code which
// is not the idiomatic way when using Typesafe Config.
Long timeout = configuration.getMilliseconds("my.service.timeout", 5000); // 5 seconds
After:
# This is declared in `conf/reference.conf`, but for applications you
# can declare it directly inside `conf/application.conf` file.
my.service.timeout = 5 seconds
And you can eventually override the value in your application.conf
file:
# This will override the value declared in reference.conf
my.service.timeout = 10 seconds
As stated above, this is specially useful when creating modules, since your module can provide reference values that are easy to override. Your Java code will then look like:
// Where config is an instance of com.typesafe.config.Config
Long timeout = config.getDuration("my.service.timeout");
§Manually checking values
If you don’t want or if you cannot have reference values, you can use Config.hasPath
or Config.hasPathOrNull
to check if the value is configured before accessing it. This is a better option if the configuration is required but you can provide a reference (default) value:
import com.typesafe.config.Config;
import com.typesafe.config.ConfigException;
public class EmailServerConfig {
private static final String SERVER_ADDRESS_KEY = "my.smtp.server.address";
private final Config config;
@javax.inject.Inject
public EmailServerConfig(Config config) {
this.config = config;
}
// The relevant code is here. First use `hasPath` to check if the configuration
// exists and, if not, throw an exception.
public String getSmtpAddress() {
if (config.hasPath(SERVER_ADDRESS_KEY)) {
return config.getString(SERVER_ADDRESS_KEY);
} else {
throw new ConfigException.Missing(SERVER_ADDRESS_KEY);
}
}
}
Next: Play 2.5