1

我的资源文件夹中的文件很少,并且我有一个相同的映射类。现在我想要的只是使用 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
  }

有没有最简单的方法?

4

1 回答 1

2
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])
于 2020-09-08T21:12:56.737 回答