强制 pureconfig 使用 -dconfig.file application.conf 文件而不是资源 application.conf

force pureconfig to use -dconfig.file application.conf file and not resource application.conf

我有以下 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

它使用资源 application.conf 文件,尽管参数中有 -Dconfig.file。 你有什么想法吗?

调用的问题

ConfigFactory.load("application.conf")

来自 scaladocs

Loads an application's configuration from the given classpath resource or classpath resource basename, sandwiches it between default reference config and default overrides, and then resolves it.

你必须使用

ConfigFactory.load()

哪个

Loads a default configuration, equivalent to load(defaultApplication())

并且defaultApplication支持config.file

If the system properties config.resource, config.file, or config.url are set, then the classpath resource, file, or URL specified in those properties will be used rather than the default application.{conf,json,properties} classpath resources.