如何从.scala文件中获取所有配置参数? [英] How to get all config parameters from a .scala file ?

查看:81
本文介绍了如何从.scala文件中获取所有配置参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从另一个scala类的 BeamConfig.scala 中调用所有参数.存储在 BeamConfig.scala 中的参数如下:

I want to call all the parameters from BeamConfig.scala in another scala class. The parameters stored in BeamConfig.scala are like below:

case class WarmStart(
  enabled: scala.Boolean,
  path: java.lang.String
)

object WarmStart {

  def apply(c: com.typesafe.config.Config): BeamConfig.Beam.WarmStart = {
    BeamConfig.Beam.WarmStart(
      enabled = c.hasPathOrNull("enabled") && c.getBoolean("enabled"),
      path = if (c.hasPathOrNull("path")) c.getString("path") else "output"
    )
  }
}

因此,与BeamConfig.scala中的上述对象类似,有100多个参数对象.如果我想从该文件中获取参数,则将执行以下操作:

So There are more than 100 parameters object like above object in BeamConfig.scala. If I want to get the parameter from this file than I will do like this:

beam.warmStart.enable
beam.warmStart.path

beam是根类,所以有什么方法可以让我批量调用所有参数,也可以将所有对象存储在Map或其他对象中.谢谢

Where beam is the root class.So is there any way so that i can call all the parameters in a bulk or I can store all the object in some Map or something else. Thanks

推荐答案

您可以通过以下几种不同的方式进行此操作:

there's a couple different ways you could do this:

以某种有点不安全的方式使用Typesafe Config: https://github.com/lightbend/config#api-example

Using Typesafe Config in a somewhat unsafe-ish manner: https://github.com/lightbend/config#api-example

这将为您提供类似地图的访问权限,但如果名称错误,类型不对齐等,它很容易爆炸.

This would give you map-like access but it can very easily explode if the names are wrong, types don't line up etc.

使用PureConfig(类型安全配置周围的包装器,可以自动派生基于案例类的配置解码器,有点像json的circe) https://pureconfig.github.io/docs/

Using PureConfig (a wrapper around typesafe config which allows automatic derivation of case class based config decoders, kinda like circe for json) https://pureconfig.github.io/docs/

因此,您必须一次编写包含100个字段的大型caseclass,但是必须对该case类进行安全的config解码,然后再使用具有正确类型的普通命名属性.

So you'd have to write you large caseclass with 100 fields once but you have a safe decoding of config into that case class and after that you have normal named properties with their correct types.

(请注意,这将使您在重命名重构下失去不变性)

(Note that this will lose you invariance under rename refactor)

这篇关于如何从.scala文件中获取所有配置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆