首页 > 解决方案 > koin 如何与 android 中的属性一起使用?

问题描述

我在官方 koin 文档中发现属性默认位置是src/main/resources/koin.properties,但是当我尝试使用它时,我得到了这个漂亮的异常。有人可以解释一下 koin 如何与 Android 上的属性一起工作吗?

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app.AppApplication, PID: 12387
    java.lang.RuntimeException: Unable to create application com.example.app.AppApplication: org.koin.core.error.NoPropertyFileFoundException: No properties found for file 'koin.properties'
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6608)
        at android.app.ActivityThread.access$1500(ActivityThread.java:235)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:225)
        at android.app.ActivityThread.main(ActivityThread.java:7563)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
     Caused by: org.koin.core.error.NoPropertyFileFoundException: No properties found for file 'koin.properties'
        at org.koin.core.registry.PropertyRegistry.loadPropertiesFromFile(PropertyRegistry.kt:100)
        at org.koin.core.KoinApplication.fileProperties(KoinApplication.kt:92)

使用 onCreate() 类:

override fun onCreate() {
        super.onCreate()
        startKoin {
            androidLogger(Level.NONE)
            androidContext(this@AppApplication)
                
            //copied from docs
            // Load properties from the default location 
            // (i.e. `/src/main/resources/koin.properties`)
            fileProperties("koin.properties") //CRASH

            modules(appModule)
        }
    }

标签: javaandroidkotlinpropertieskoin

解决方案


事情是我应该使用 use fileProperties(),而不是参数fileProperties("filename")。然后只需使用getProperty("property_name").

那是因为/src/main/resources/koin.properties默认位置包括文件名......


推荐阅读