Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

playframework - Can we use Google Guice DI with a Scala Object instead of a Scala class in Play 2.4 with scala

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.

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)
    }
  }
}

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 {

}

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

Controller

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...