在 Play! v1 中,定义配置变量在 application.conf
中非常容易,并且可以像这样访问它们:
play.configuration("db.driver")
然而,我现在在v2的文档中找不到类似用法的内容,也没有适当的替代方法。有什么方法可以实现这个目标吗?
在 Play! v1 中,定义配置变量在 application.conf
中非常容易,并且可以像这样访问它们:
play.configuration("db.driver")
然而,我现在在v2的文档中找不到类似用法的内容,也没有适当的替代方法。有什么方法可以实现这个目标吗?
在 Play 2.0 中,相当于这个的 Scala 实现是:
Play.current.configuration.getString("db.driver")
你还需要 import play.api.Play
有关此的完整文档在这里。
play.api.Play.maybeApplication.map(_.configuration.getString("db.driver"))
。 - Andy Petrella适用于Play 2.0 - 在Java控制器中,您可以使用以下内容:
String optionValue = Play.application().configuration().getString("db.driver");
要在视图中获取变量,请使用以下代码:
@play.Play.application().configuration().getString("db.driver")
从Play 2.5版本开始,play.api.Play.current
已被弃用。您应该使用依赖注入来注入Environment
或Configuration
,并使用它们来读取配置值:
class HomeController @Inject() (configuration: play.api.Configuration) extends Controller {
def config = Action {
Ok(configuration.underlying.getString("db.driver"))
}
}
查看Play文档以了解更详细的讨论。
在Java的Play 2.3.2中,您可以使用com.typesafe.config.ConfigFactory
选项:
Config conf = ConfigFactory.load();
String myFooBarConfiguration = conf.getString("foo.bar");
快速移动的API!
在Play 2.3[.8] / Java
中测试了另一种访问application.conf
的值的方法:
要检查Play
版本,请检查文件project/plugins
。包含“sbt-plugin”的行应该有一个版本规范,如“2.3.8”。
例如,如果application.conf
包含以下内容:
myConfigStringValue=abc
myConfigBooleanValue=true
可以从Java文件/类中查询这些值,例如:
import play.Configuration;
...
String myString = Configuration.root().getString("myConfigStringValue");
Boolean myBoolean = Configuration.root().getBoolean("myConfigBooleanValue");
如果未找到该值,get...方法将返回null,还有一些get...方法需要一个默认值作为参数。
详见https://www.playframework.com/documentation/2.3.x/api/java/index.html,并检查play.Configuration类。
conf/application.conf
读取一个值,您可以执行以下操作:import play.api.Play.current
...
current.configuration.getString("db.driver")
使用Play> 2.5.X中的Java技术,您可以通过ConfigFactory助手读取配置值:
ConfigFactory.load().getString("redis.url")
ConfigFactory.load().getInt("redis.port")
Config对象将把参数转换为正确的类型。它公开处理任何Java类型的方法(getDouble,getLong等)。详情请参阅文档。import play.Application.*;
...
String optionValue = play.Play.application().configuration().getString("my.config");
play.api.Play
包,并使用以下代码获取变量名:Play.current.configuration.getString("varibale name")
。@Singleton
class RESTSessionChecker @Inject()(
implicit override val conf: Configuration)
extends Filter {
val MAX_CONCURRENT_REQUESTS = conf.getString("MAX_CONCURRENT_REQUESTS").
getOrElse("100").toInt
...