我希望在我的koin应用程序中有一个可空的bean,比如:
single(named("NULLABLE")) {
System.getenv("NULLABLE")
}即,如果设置了环境变量"NULLABLE“,则名为"NULLABLE”的bean (此处为字符串)将具有其值,否则将为null。
用法可能如下:
init {
startKoin {
modules(listOf(module))
}
}
val nullableString: String? by inject(named("NULLABLE"))但是,如果没有名为"NULLABLE“的环境变量,我会得到一个异常:
Exception in thread "main" java.lang.IllegalStateException: Single instance created couldn't return value
at org.koin.core.instance.SingleDefinitionInstance.get(SingleDefinitionInstance.kt:42)
at org.koin.core.definition.BeanDefinition.resolveInstance(BeanDefinition.kt:70)
at org.koin.core.scope.Scope.resolveInstance(Scope.kt:165)
at org.koin.core.scope.Scope.get(Scope.kt:128)这是因为当工厂的lambda返回null时,SingleDefinitionInstance会抛出一个异常:
override fun <T> get(context: InstanceContext): T {
if (value == null) {
value = create(context)
}
return value as? T ?: error("Single instance created couldn't return value")
}在Koin中可以有一个可空(可选)的bean吗?
发布于 2020-07-14 14:30:47
我没有找到一种有效的官方方式。我用下面的代码片段解决了我的问题:
val data: ClassModel? = try {
get(named("YourNamedValue"))
} catch (e: InstanceCreationException) {
null
} catch (e: IllegalStateException) {
null
}https://stackoverflow.com/questions/57527303
复制相似问题