3

我已经开始使用 MacWire 对我的 Play 应用程序进行依赖注入,但在尝试注入数据库连接时遇到了问题。

在使用 DI 之前,我的代码如下所示:

DB.withConnection { implicit connection =>
  ...
}

这在使用 DI 后不再起作用。我得到以下异常:java.lang.InstantiationException: play.api.db.DBApi.

我的应用程序加载器:

class Loader extends ApplicationLoader {
  def load(context: Context) = {
    val components = new BuiltInComponentsFromContext(context) with Components
    components.application
  }
}

应用程序的主要组件:

trait Components extends BuiltInComponents with I18nComponents
                 with RepositoryModule {

  lazy val assets: Assets = wire[Assets]
  lazy val router: Router = wire[Routes] withPrefix "/"
}

和存储库模块:

trait RepositoryModule {
  lazy val userRepository = wire[UserRepository]
}

如何获取和使用数据库连接池并将其注入以便可以在存储库中使用?

4

1 回答 1

2

我使用. DBComponents_ 有了它们,我可以得到一个对象并将其注入到存储库中。这是我用于模块的代码:BoneCPComponentsRepositoryModuleDatabase

trait RepositoryModule extends BuiltInComponents with DBComponents with BoneCPComponents {
  lazy val database: Database = dbApi.database("default")
  lazy val userRepository = wire[UserRepository]
}

数据库“默认”将db.default使用application.conf. 此解决方案的主要问题是您需要从池中获取连接并在完成后返回它们。我不知道是否可以改进以模仿该withConnection方法。

使用注入数据库的用户存储库示例:

class UserRepository(db: Database) {
  def deleteAdults: Unit = {
    val connection: Connection = db.getConnection()
    val removed: Int = SQL("DELETE * FROM User WHERE age > 18").executeUpdate()(connection)
    connection.close()
  }
}
于 2015-11-20T20:47:17.463 回答