我有同样的挣扎,我想出了这样的解决方案(使用第二种方法):
创建一个供 DAO 使用的上下文:
trait BaseContext{
def dbName: String
val dbConfig = DatabaseConfigProvider.get[JdbcProfile](dbName)
val db = dbConfig.db
val profile = dbConfig.driver
val tables = new Tables { // this is generated by Schema Code Generator
override val profile: JdbcProfile = dbConfig.driver
}
}
@Singleton
class AppContext extends BaseContext{
def dbName = "mysql" // name in your conf right after "slick.dbs"
}
@Singleton
class TestingContext extends BaseContext{
def dbName = "h2"
}
然后创建一个模块来绑定注入,别忘了在conf中使用play.modules.enabled += "your.Module"启用它:
class ContextModule(environment: Environment, configuration: Configuration) extends AbstractModule {
override def configure(): Unit = {
if (configuration.getString("app.mode").contains("test")) {
bind(classOf[BaseContext])
.to(classOf[TestingContext])
} else {
bind(classOf[BaseContext])
.to(classOf[AppContext])
}
}
}
并将其注入您创建的每个 DAO:
class SomeDAO @Inject()(context: BaseContext){
val dbConfig = context.dbConfig
val db = context.db
val tables = context.tables
import tables.profile.api._
def otherStuff....
// you can call db.run(...), tables.WhateverYourTableIs, tables.TableRowCaseClass, ...
}
最后一步,您的配置文件。在我的例子中,我使用app.mode 来标记环境,我使用单独的.conf 来标记不同的环境。当然,在这些配置中,您必须具有正确的数据库配置。这是示例:
app.mode = "test"
# Database configuration
slick.dbs = {
# for unit test
h2 {
driver = "slick.driver.H2Driver$"
db = {
url = "jdbc:h2:mem:test;MODE=MYSQL"
driver = "org.h2.Driver"
keepAliveConnection = true
}
}
}
我很确定我的解决方案不是一个优雅的解决方案,但它可以交付货物。 :)
欢迎任何更好的解决方案!