我曾经使用 Play.current.configuration.getString('NAME_HERE')
在 Play 2.4.x 中获取 application.conf
变量,它运行良好在类、对象和伴随对象中也是如此。
现在,我在一个新项目中使用 Play 2.5.4 和 Scala,我不会使用这个 Play.current
,因为它已被弃用,但有一个使用 DI 的替代方案,像这样:
class HomeController @Inject() (configuration: play.api.Configuration) extends Controller {
def config = Action {
Ok(configuration.underlying.getString("db.driver"))
}
}
这个 DI 注入(inject)在类里面就像一个魅力,但在这个项目中,我需要在对象中获取变量 db.driver
?据我所知,对于对象我不能使用 DI。
也许使用 Guice 会有帮助?
最佳答案
你可以使用@Singleton
注解类代替object
trait Foo {}
@Singleton
class FooImpl @Inject()(configuration: play.api.Configuration)) extends Foo {
//do whatever you want
}
@Singleton
使类成为单例。感觉有点尴尬,因为 Scala 本身具有语法 object
来创建单例,但这是最简单且可能是最好的解决方案DI 成单例。
您也可以像下面的代码一样热切地创建单例。
bind(classOf[Foo]).to(classOf[FooImpl])asEagerSingleton()
更多详细信息,您可以查找Google Guice Wiki和 Playframework site
编辑
你怎么调用它和你在Playframework2.5中如何DI是完全一样的。
class BarController @Inject()(foo: Foo) extends Controller {
//Do whatever you want with Foo
}
Guice 基本上会在您每次 DI 时生成新的实例,一旦您放置 @Singleton
,Guice 将只使用一个实例。
DI 用于反高耦合。所以当你想使用你从另一个类定义的类时,你需要 DI 否则这些类是高度耦合的,最终会使你的单元测试代码变得更难。
仅供引用,您可以通过这种技术在 Play 之外使用它们。
Create an Instance of class which does DI via Playframework Guice Independently in Scala
关于scala - 如何使用 Scala 和 Play 2.5.x 在对象中获取 application.conf 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38612446/