在playframework< 2.5我们可以使用
val value = Play.current.configuration.getString("confKey")
但在2.5中我们有警告
对象Play中的方法当前不推荐使用:这是对应用程序的静态引用,而是使用DI
package tmp
object TmpObj {
val confVal = ??? // read key-value from application.conf or *.conf
}
所以,我的问题是 - “如何从项目使用DI
中的任何对象中读取conf?”
请帮助我理解我必须在 ??????
中撰写的内容,以便从application.conf
或其他somePath/file.conf
获取价值
import javax.inject.Inject
import play.api.Configuration
class AppConfig @Inject() (configuration: play.api.Configuration) {
val someConfValue = configuration.underlying.getString("someConfValue")
}
object ConfigReader extends AppConfig(??????) {
def getSomeConfValue() = someConfValue
}
println(ConfigReader.getSomeConfValue())
答案 0 :(得分:0)
由于AppConfig需要“配置”对象,因此其实例创建需要该对象。使用@Inject()表示法告诉DI框架它需要在编译时提供这种依赖。
因此,有两种方法可以解决您想要实现的目标: 而不是定义对象定义一个类ConfigReader:
class ConfigReader(config: play.api.Configuration) extends AppConfig(config) {
def getSomeConfValue() = someConfValue
}
或者既然您已经介绍了DI框架,那就让它为您处理所有依赖项。
class ConfigReader @Inject() (appConfig: AppConfig) {
def getSomeConfValue() = appConfig.someConfValue
}
然后在需要ConfigReader
的任何地方注入它。
答案 1 :(得分:0)
为此我创建了文件services / ConfigReader.scala
package services
import javax.inject.Inject
import play.api.{Configuration, Environment}
class AppConfig @Inject()(playConfig: Configuration) {
val dbHost: Option[String] = playConfig.getString("mydb.host")
val dbPort: Option[Long] = playConfig.getLong("mydb.port")
}
object ConfigReader {
val config = new AppConfig(Configuration.load(Environment.simple()))
def getDbHost: String = config.dbHost.getOrElse("localhost")
def getDbPort: Long = config.dbPort.getOrElse(27017)
}
我在conf / application.conf中指定了
mydb {
host = 192.168.0.0
port = 1234
}
我有机会通过导入我的ConfigReader从任何位置访问配置,例如在控制器中
package controllers
import play.api.mvc._
import services.ConfigReader
class SomeCtrl extends Controller {
def index = Action { request =>
Ok(ConfigReader.getDbHost + ":" + ConfigReader.getDbPort.toString)
}
}
它的工作正常,但我仍然希望从myconf/myconf.conf
执行此操作并寻找方法