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

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

问题描述

我们的应用程序基于使用Scala 2.11和Akka的Play 2.4 构建. 缓存在我们的应用程序中使用率很高.我们使用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.

我们当前使用缓存对象(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对象而不是scala类来实现Google Guice DI ?

推荐答案

否,无法在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
}

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

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