我已经开始使用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]
}我如何获得和使用数据库连接池并注入它,以便它可以在存储库中使用?
发布于 2015-11-20 20:47:17
我使用DBComponents和BoneCPComponents在RepositoryModule中的特性来解决它。有了它们,我可以得到一个Database对象,将它注入到存储库中。这是我为模块使用的代码:
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()
}
}https://stackoverflow.com/questions/32544800
复制相似问题