訣竅是將初始化放在注入類的構造函數中。這裏有一個例子:
添加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])
}
}
添加在conf/application.conf
:
play.modules.enabled += "DatabaseModule"
這就是開始。 .asEagerSingleton
將運行構造函數代碼,而無需注入它。當你要選擇注入其中一個,那麼你需要刪除.asEagerSingleton
並加載相應的數據庫實現兩種:基於configuration in the bindings