【问题标题】:How To Load and Read Configuration in the Play Framework Guice Module如何在 Play Framework Guice 模块中加载和读取配置
【发布时间】:2021-11-18 17:49:02
【问题描述】:

问题:

我知道我们可以在 Play 框架应用程序的其余部分中注入配置模块,但我想在模块配置期间获取我的 appliciation.conf 信息。我该怎么做?

   class BaseModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {

    override def configure(): Unit = {
        val onAzure = ??? // < How can I pull configuration here?
        if (onAzure) {
        bind[PersonService].to[AzurePersonService]
        } else {
        bind[PersonService].to[AWSPersonService]
        }
    }

【问题讨论】:

    标签: playframework guice


    【解决方案1】:

    解决方案:

    您可以在模块文件中手动实例化Configuration。

        import com.typesafe.config.ConfigFactory
        import play.api.Configuration
    
    
        class BaseModule extends AbstractModule with ScalaModule with AkkaGuiceSupport {
        private val logger = Logger(this.getClass)
    
        override def configure(): Unit = {
            val config = new Configuration(ConfigFactory.load())
            val onAzure = config.get[Option[Boolean]]("cloud.mode.onAzure").getOrElse(false)
            if (onAzure) {
            bind[PersonService].to[AzurePersonService]
            } else {
            bind[PersonService].to[AWSPersonService]
            }
        }
    

    【讨论】:

    • 如果您希望能够覆盖/注入配置,例如编写单元测试时,必须将 Configuration 实例注入 BaseModule 类(使用 Guice 依赖注入)。之后,您可以制作一个 Config 对象并构建您的测试应用程序,如下所示:myTestConfig = ...; new GuiceApplicationBuilder().loadConfig(myTestConfig)。然后 myTestConfig 将被注入到您的 BaseModule 类中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多