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

Play Framework Guice模块中如何加载读取application.conf配置

解决方案

Play 框架启动加载自定义模块时,会自动为带有(Environment, Configuration)签名构造函数的模块注入对应实例,直接声明构造参数即可在configure方法中读取application.conf的配置:

class BaseModule(environment: Environment, config: Configuration) extends AbstractModule with ScalaModule with AkkaGuiceSupport {

    override def configure(): Unit = {
        // 替换为你实际在application.conf中定义的配置键
        val onAzure = config.get[Boolean]("cloud.provider.azure")
        if (onAzure) {
            bind[PersonService].to[AzurePersonService]
        } else {
            bind[PersonService].to[AWSPersonService]
        }
    }
}

如果你的绑定逻辑更复杂,也可以用@Provides注解的方式实现,无需把逻辑写在configure方法中:

import com.google.inject.Provides

class BaseModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {

    override def configure(): Unit = {}

    @Provides
    def bindPersonService(config: Configuration): PersonService = {
        val onAzure = config.getOptional[Boolean]("cloud.provider.azure").getOrElse(false)
        if (onAzure) {
            new AzurePersonService()
        } else {
            new AWSPersonService()
        }
    }
}

注意:如果对应的配置键可能不存在,可以用getOptional方法获取配置并设置默认值,避免应用启动时报配置缺失错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:24:07