我有一个用于配置参数的案例类,该类在启动实际应用程序之前已填充(使用NO外部库)。 我在整个应用程序中和太多地方传递了此配置对象。 现在的问题是,可以将该对象设置为全局对象,以便在应用程序中将其引用,因为值将保持不变。
case class ConfigParam() extends Serializable {
var JobId: Int = 0
var jobName: String = null
var snapshotDate: Date = null
}
val configParam = ???
val ss = getSparkSession(configParam) //Method call...
答案 0 :(得分:2)
使用ConfigParam作为全局对象可能会对您造成不良影响。首先,这将使测试使用该全局对象的任何功能变得更加困难。
也许您可以只将ConfigParam
作为隐式参数传递?
例如,假设您有3个功能:
def funA(name: String)(implicit configParam: ConfigParam): String = ???
def funB(number: Int)(implicit configParam: ConfigParam): String = ???
//you don't have to explicitily pass config param to funA or funB
def funC(name: String)(implicit configParam: ConfigParam): String = funA(name) + funB(100)
implicit val configParam = ??? //you need to initialise configParams as implicit val
funC("somename") //you can now just call funC without explicitly passing configParam
//it will be also passed to all function calls inside funC
//as long as they've got implicit parameter list with ConfigParam
另一种解决方案可能是使用某种依赖注入框架,例如guice。