1

我有以下 application.conf 文件:

# App
tables = [
    "table_1",
    "talbe_2"
]

和以下scala代码:

import pureconfig._
import pureconfig.generic.auto._
import com.typesafe.config.ConfigFactory
import pureconfig.generic.ProductHint

case class Configuration(tables: Array[String])

object Config {
  implicit def hint[A] = ProductHint[A](ConfigFieldMapping(CamelCase, CamelCase))

  val conf = ConfigSource.fromConfig(ConfigFactory.load("application.conf")).load[Configuration] match {
    case Right(conf) => conf
    case Left(failures) => throw new Exception(s"Unable to load the configuration ${failures.toList.mkString("\n")}")
  }
}

并测试application.conf,我有这个代码:

object Test extends App {

  val res = Config.conf.tables
  println("hello")
}

当我将 application.conf 放在资源文件夹中时,它可以工作。但是当我使用它时它不起作用

-Dconfig.file=C:/Users/path/to/application.conf

尽管参数 -Dconfig.file 中有一个,但它使用资源 application.conf 文件。你有什么主意吗?

4

1 回答 1

3

问题是电话

ConfigFactory.load("application.conf")

来自 scaladocs

从给定的类路径资源或类路径资源基名加载应用程序的配置,将其夹在默认引用配置和默认覆盖之间,然后解析它。

你必须使用

ConfigFactory.load()

哪个

加载默认配置,相当于 load(defaultApplication())

defaultApplication支持config.file

如果设置了系统属性 config.resource、config.file 或 config.url,则将使用这些属性中指定的类路径资源、文件或 URL,而不是默认的 application.{conf,json,properties} 类路径资源.

于 2020-09-29T21:03:38.090 回答