我们可以在带有 Scala 的 Play 2.4 中使用带有 Scala 对象的 Google Guice DI 而不是 Scala 类吗 [英] Can we use Google Guice DI with a Scala Object instead of a Scala class in Play 2.4 with scala

查看:23
本文介绍了我们可以在带有 Scala 的 Play 2.4 中使用带有 Scala 对象的 Google Guice DI 而不是 Scala 类吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序基于 Play 2.4 和 Scala 2.11 和 Akka.缓存在我们的应用程序中大量使用.我们使用 Play 的默认 EhCache 进行缓存.

Our application is built on Play 2.4 with Scala 2.11 and Akka. Cache is used heavily in our application.We use Play's default EhCache for caching.

我们目前使用Cache 对象(play.api.cache.Cache) 来缓存

We currently use the Cache object(play.api.cache.Cache) for Caching

import play.api.Play.current
import play.api.cache.Cache

object SampleDAO extends TableQuery(new SampleTable(_)) with SQLWrapper {
  def get(id: String) : Future[Sample] = {
    val cacheKey = // our code to generate a unique cache key
    Cache.getOrElse[Future[[Sample]](cacheKey) {
      db.run(this.filter(_.id === id).result.headOption)
    }
  }
}

现在,在 Play 2.4 中,我们计划利用内置的 Google Guice DI 支持.以下是 Play 2.4 文档提供的示例示例

Now with Play 2.4 we plan to make use of the inbuilt Google Guice DI support. Below is a sample example provided by the Play 2.4 docs

import play.api.cache._
import play.api.mvc._
import javax.inject.Inject

class Application @Inject() (cache: CacheApi) extends Controller {

}

以上示例将依赖项插入到Scala 类构造函数中.但是在我们的代码中 SampleDAO 是一个 Scala 对象而不是类.

The above example inserts dependency into a Scala class constructor. But in our code SampleDAO is a Scala object but not class .

那么现在是否可以使用 scala 对象来实现 Google Guice DI 而不是 scala 类?

So now Is it possible to implement Google Guice DI with A scala object instead of a scala class ?

推荐答案

不,不能在 guice 中注入对象.将您的 SampleDAO 改为一个类,在其中注入 CacheApi.然后在控制器中注入新的 DAO 类.您还可以使用 @Singleton 注释 SampleDAO.这将确保 SampleDAO 只会被实例化一次.整个事情看起来像这样:

No, it is not possible to inject objects in guice. Make your SampleDAO a class instead, where you inject CacheApi. Then inject your new DAO class in your controllers. You can additionally annotate SampleDAO with @Singleton. This will ensure SampleDAO will be instantiated only once. The whole thing would look something like this:

DAO

@Singleton
class SampleDAO @Inject()(cache: CacheApi) extends TableQuery(new SampleTable(_)) with SQLWrapper {
  // db and cache stuff
}

控制器

class Application @Inject()(sampleDAO: SampleDAO) extends Controller {
  // controller stuff
}

这篇关于我们可以在带有 Scala 的 Play 2.4 中使用带有 Scala 对象的 Google Guice DI 而不是 Scala 类吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆