How to do database initialization when using DI in Play 2.4?

天大地大妈咪最大 提交于 2019-12-03 22:28:35

The trick is to place the initialisation in the constructor of the injected class. Here's an example:

Add app/modules/Database.scala:

package modules

import com.google.inject.AbstractModule
import com.google.inject.name.Names

trait Database {
  def create(): Unit
  def drop(): Unit
}

class TestDatabase extends Database {
  initialize() // running initialization in constructor
  def initialize() = {
    println("Setup database with test data here")
  }
  def create() = ()
  def drop() = ()
}

class ProdDatabase extends Database {
  // similar to above
}

class DatabaseModule extends AbstractModule {
  def configure() = {
    bind(classOf[Database])
      .annotatedWith(Names.named("development"))
      .to(classOf[TestDatabase]).asEagerSingleton
    bind(classOf[Database])
      .annotatedWith(Names.named("production"))
      .to(classOf[TestDatabase])
  }
}

Add in conf/application.conf:

play.modules.enabled += "DatabaseModule"

That's to start with. The .asEagerSingleton will run the constructor code without needing you to inject it. When you want to choose which one to inject, then you'd need to remove the .asEagerSingleton and load the appropriate database implementation either:

  • based on configuration in the bindings (see link for example); or
  • in the service/controller, for example:

    @Inject @Named("development") Database database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!