Ktor - 在 Application.module 函数中访问由 main 函数初始化的变量
Ktor - Access variable initilized by main function in Application.module function
var foo : String? = null
fun main(args: Array<String>): Unit {
foo = "Hello World"
io.ktor.server.netty.EngineMain.main(args)
}
@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
// foo is null here
}
如何在 Application.module
中访问 foo
,为什么这是一个问题?
您可以按以下格式传递任意参数:-P:<argument>
其中 <argument>
是您的参数的实际名称。在 Application.module
中,您可以通过 config
对象访问它们:
fun Application.main() {
println(environment.config.property("<argument>").getString())
}
您无法在模块中访问此类变量,因为 Ktor 在不同的类加载器中加载您的应用程序(和模块 ofc)。
当您调用 EngineMain.main()
时,它会经过一长串调用,其中一个步骤是在 createApplication()
方法 here. The implementation of createClassLoader()
is here.[=14 中创建一个新的类加载器=]
var foo : String? = null
fun main(args: Array<String>): Unit {
foo = "Hello World"
io.ktor.server.netty.EngineMain.main(args)
}
@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
// foo is null here
}
如何在 Application.module
中访问 foo
,为什么这是一个问题?
您可以按以下格式传递任意参数:-P:<argument>
其中 <argument>
是您的参数的实际名称。在 Application.module
中,您可以通过 config
对象访问它们:
fun Application.main() {
println(environment.config.property("<argument>").getString())
}
您无法在模块中访问此类变量,因为 Ktor 在不同的类加载器中加载您的应用程序(和模块 ofc)。
当您调用 EngineMain.main()
时,它会经过一长串调用,其中一个步骤是在 createApplication()
方法 here. The implementation of createClassLoader()
is here.[=14 中创建一个新的类加载器=]