scala/typesafe Config 是否提供了一些方法来配置特征的可插入实现?

Does scala/typesafe Config offer some way how to configure pluggable implementation of the trait?

我面临以下任务,即提供特性的实现作为配置选项。 我有以下 class 层次结构:

trait Storage {
  def store()
}

object LocalStorage extends Storage {
   def store(){ ... }
}

object RemoteStorage extends Storage {
   def store(){ ... }
}

在 属性 文件中有一个配置:

storage.class = "com.xxx.LocalStorage"

在持久层上实现:

class CheckPersister{
val storageType = ConfigFactory.load().getString("storage.class")
val storage: Storage = Class.forName(storageType).asInstanceOf[Storage]
...
}

有没有更好的方法来处理这种配置?我正在使用类型安全配置。

感谢

在配置文件中直接指定 class 的名称看起来不是个好主意。这样的东西可以接受吗?

storage.location = "local"

class CheckPersister {
  val storageType = ConfigFactory.load().getString("storage.class")
  val storage: Storage = storageType match {
    case "local" => LocalStorage
    case "remote" => RemoteStorage
    case x => throw new RuntimeException(s"Invalid storage type $x specified")
  }
  ...
}

这样你就不会意外地实例化一个你不想要的class。