How to change Play 2 Framework DB configuration at runtime? How to change Play 2 Framework DB configuration at runtime? database database

How to change Play 2 Framework DB configuration at runtime?


The key is to use the ConfigFactory to create a new Config entry. This new Config contains an entry for password with the value coming from your http call to your password service.

A new Configuration is created using the new Config, which in turn falls back to the original Config from the original Configuration.

Basically the new password entry supersedes the original.

It sound long winded when you say it, but the code is pretty readable.

public class Global extends GlobalSettings {    // inject http client to make call for password    @Override    public Configuration onLoadConfig(Configuration configuration, File file, ClassLoader classLoader) {        final Config config = ConfigFactory.parseString(String.format("db.default.user=%s", callPasswordService()));        return new Configuration(config.withFallback(configuration.getWrappedConfiguration().underlying()));    }}


To answer my own question, at first we solved the problem of updating the immutable configuration at runtime by overriding Configuration.onLoadConfig with the following:

  1. If configuration indicates that production.level is PROD
  2. Read the password from stdin
  3. Create a new configuration by converting the old one to a map and building a new one with ConfigFactory.parseMap, with the new parameter as well
  4. Return super.onLoadConfig

However, this still didn't address that the problem of reloading the DB configuration. In the end, my colleague created a Play! plugin which essentially a copy of some JPA classes with the added capability of being reloaded with a Map of configuration properties.

Update

The "hook" is the additional static method which the plugin adds to the JPA class (e.g. reloadWithProperties). This method creates a new data source which is then rebound in JNDI.