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

