【问题标题】:Slick database configuration光滑的数据库配置
【发布时间】:2016-01-01 06:58:11
【问题描述】:

我的 Play 应用程序 (Play 2.4.3) 中的 Slick 配置存在问题。 我阅读了documentation article,但想将 dbConfig 从控制器移动到指定的 trait 并将这个 trait 混合到存储库类中。

项目中有几个文件:ClientRepository (class), BaseClientRepository (trait) 和 BaseDbRepository (trait)。

trait BaseDbRepository {
  val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)
  import dbConfig.driver.api._

  def withConnection[T](f: => DBIOAction[T, NoStream, Nothing]) = {
    dbConfig.db.run(f)
  }
}

trait BaseClientRepository {
  def getById(id: Int): Future[Client]
  def getByLocation(location: String): Future[Seq[Client]]
}

class ClientRepository extends BaseDbRepository with BaseClientRepository {

  def getById: Future[Client] = withConnection {
    ...
  }

  def getByLocation: Future[Seq[Client]] = withConnection {
    ...
  }
}

这对我的客户端控制器很有效:

class Client extends Controller {
  def getById(id: Int) = ???
}

但是当我尝试将 DI 与 Guice 一起使用时:

class Client @Inject()(clientRepository: BaseClientRepository) extends Controller {
  def getById(id: Int) = Action.async {
    // I try to use client repository here
  }
}

它失败并出现以下异常 CreationException: 无法创建注入器,看到如下错误:

1) 捕获并报告异常。消息:没有启动的应用程序 在 com.google.inject.util.Modules$OverrideModule.configure(Modules.java:177)

我尝试将此定义 val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current) 移动到 Global.scala 中,它可以正常工作,但现在我不推荐使用 Global.scala。

那么,最好的地方在哪里?

更新:我使用注入模块进行 DI 配置:

class InjectionModule extends AbstractModule {
  def configure() {
    bind(classOf[BaseClientRepository]).toInstance(new ClientRepository)
  }
}

【问题讨论】:

    标签: scala playframework slick slick-3.0


    【解决方案1】:

    dbConfig 在这种情况下应该是一个惰性值或函数。 这对我有用:

    private lazy val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)
    

    【讨论】:

      【解决方案2】:

      Guice 未能注入 BaseClientRepository 的实现,注解 @ImplementedBy 可以提供帮助。

      @ImplementedBy(classOf[ClientRepository])
      trait BaseClientRepository {
         def getById(id: Int): Future[Client]
         def getByLocation(location: String): Future[Seq[Client]]
      }
      

      【讨论】:

      • 不幸的是它没有帮助。例外是一样的:没有启动的应用程序......我已经用我的 Guice 配置更新了帖子。
      猜你喜欢
      • 2017-09-09
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多