Ernest Sadykov Ernest Sadykov - 3 years ago 122
Scala Question

Inject configuration value in play framework using Guice

I have play web application with

(nothing unusual). Guice is used for dependency injection. How can property value be injected in class constructor? The code is below.

class MyController @Inject() (private val foo: Foo) extends Controller {

trait Foo {
def bar: String

class FooImpl extends Foo {
override val bar = current.configuration.getString("").get

In the current configuration
can't be tested without running application. I want to be able instantiate
in unit tests. The perfect solution [from my point of view] should look like that:

class FooImpl @Inject() (@Named("") override val bar: String) extends Foo {

Unfortunately, this code doesn't work, because Guice doesn't have '' binding:

No implementation for java.lang.String annotated with was bound.

The only solution that I came up with is writing my own module, which iterates through configuration properties and binds them as named dependencies (a variation of the example from this doc). But I believe that a better approach exists.

Answer Source

I encountered the same problem after about a year, and this time come up with the following solution (very similar to the one proposed by @stranger-in-the-q and @droidman):

class InjectionModule extends AbstractModule {

  override def configure(): Unit = {

    val config: Config = TypesafeConfigReader.config
    config.entrySet().asScala.foreach { entry =>
      val path = entry.getKey
      entry.getValue.valueType() match {
        case ConfigValueType.NUMBER =>
        case ConfigValueType.BOOLEAN =>
        case ConfigValueType.STRING =>
        case _ =>

Also, this approach can be extended by appending prefixes to system properties (which key-value pairs are part of the loaded config):

private def getPrefix(configValue: ConfigValue): String = {
  val description = configValue.origin().description()
  if (description.contains("system properties")) {
  } else {

In this case instead of writing Names.named(path) one should use Names.named(getPrefix(entry.getValue) + path).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download