【问题标题】:Loading Different files from resource directory via Pureconfig通过 Pureconfig 从资源目录加载不同的文件
【发布时间】:2020-12-26 14:56:46
【问题描述】:

我的资源文件夹中的文件很少,并且我有一个相同的映射类。现在我想要的是使用 pureconfig 将每个文件加载到不同的配置类中。有没有办法通过只提供资源文件夹名称来加载它。

 - src
    - main
        - resources
            - configs
                - conf1.json
                - conf2.json

我想要这样的东西

ConfigSource.resources("configs")

它应该返回

List<Conf>

目前的做法是这样的

def main(args: Array[String]): Unit = {
    implicit def hint[A]: ProductHint[A] =
      ProductHint[A](ConfigFieldMapping(CamelCase, CamelCase))

    val resourceFiles = getResourceFolderFiles("configs")
    val configs = new ListBuffer[SampleConfig];
    resourceFiles.foreach(file =>
      configs.append(
        ConfigSource
          .file(file)
          .load[SampleConfig]
          .getOrElse(null)))
    println(configs.size)
  }

  private def getResourceFolderFiles(folder: String): Array[File] = {
    val loader = Thread.currentThread.getContextClassLoader
    val url = loader.getResource(folder)
    val path = url.getPath
    new File(path).listFiles
  }

有没有最简单的方法?

【问题讨论】:

  • 你已经尝试了什么?请分享您的最佳尝试,即使它不起作用
  • @IvanStanislavciuc 在问题中更新

标签: scala config typesafe pureconfig


【解决方案1】:
implicit def hint[A]: ProductHint[A] =
  ProductHint[A](ConfigFieldMapping(CamelCase, CamelCase))


val sampleConfigList =
  Try(Thread.currentThread().getContextClassLoader.getResource("configs").getPath)
    .flatMap(filePath => Try(new File(filePath).listFiles().toList))
    .map(fileList =>
      fileList.flatMap(file => ConfigSource.file(file).load[SampleConfig].toOption)
    )
    .getOrElse(List.empty[SampleConfig])

【讨论】:

  • Pureconfig 是否提供了直接从文件夹读取的方法?
  • 没有。它没有。
  • 我认为不需要任何更改(老实说,我不记得 scala 2.11 天)。如果您给定的代码正常工作,那么这也应该工作。
猜你喜欢
  • 2023-04-06
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多