You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala Play:能否在application.conf内定义并引用变量以避免硬编码?

在Scala Play的application.conf中定义和引用变量的正确方式

Absolutely! You can define variables in Play Framework's application.conf and reference them internally to avoid hardcoding—you just missed a small syntax detail that's easy to overlook. Play uses the HOCON (Human-Optimized Config Object Notation) format, which has specific rules for variable references.

1. 定义变量

First, define your variable just like any other config entry:

domainName = "test.com"

2. 内部引用变量

The key mistake you made was using $domainName—HOCON requires wrapping variable names in curly braces. Use ${variableName} to reference your defined variable elsewhere in the file:

# 引用domainName来拼接完整URL
app.baseUrl = "https://${domainName}"
api.endpoint = "https://api.${domainName}/v1"

进阶用法

You can take this further with some handy HOCON features:

  • Nested references: Chain variables together for more complex configs
    subDomain = "api"
    fullApiDomain = "${subDomain}.${domainName}"
    
  • Default values: Add a fallback in case the variable isn't defined (using :-)
    # 如果domainName未配置,会使用default.com作为默认值
    app.baseUrl = "https://${domainName:-default.com}"
    

验证是否生效

To confirm your references work, you can read the config in your Scala code:

import play.api.Configuration

class MyController(config: Configuration) {
  val baseUrl = config.get[String]("app.baseUrl")
  // 当domainName是"test.com"时,baseUrl会是"https://test.com"
}

The reason your initial attempt failed is that HOCON doesn't recognize bare $variable syntax—curly braces are mandatory for variable interpolation. Stick with ${domainName} and it'll work as expected!

内容的提问来源于stack exchange,提问作者Jack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:32:47