https://start.insert-koin.io/#/getting-started/koin-for-java

开始

Koin in 5 minutes (5分钟快速入手Koin)

Getting Started (开始)

下面是 koin-java 特性的简短描述。这个项目是帮助java开发人员的静态utils的一个小子集。

开始

Just use the startKoin() static function (with the static import to reduce the syntax):

只需要使用 startKoin() 静态函数(通过静态导入来减少语法):

1
2
3
4
5
6
7
8
9
10
import static org.koin.core.context.GlobalContext.start;

// Build KoinApplication instance
// Builder API style
KoinApplication koinApp = KoinApplication.create()
.printLogger()
.modules(koinModule);

// Statr KoinApplication instance
start(koinApp);

您可以访问与Kotlin startKoin() 相同的选项)。

Kotlin中的Java友好模块

你需要使用 @JvmField 标记你的module变量,以便其可以从Java中读取:

1
2
3
4
5
6
7
8
9
10
@JvmField
val koinModule = module {
single { ComponentA() }
single { ComponentB(get()) }
single { ComponentC(get(), get()) }

module("anotherModule") {
single { ComponentD(get()) }
}
}

在静态函数中注入

KoinJavaComponent 类是第一个静态的helper,他能将Koin的功能引入Java:

  • inject() - 延迟注入一个实例
  • get() - 检索实例
  • getKoin() - 获取Koin上下文
1
2
3
4
import static org.koin.java.standalone.KoinJavaComponent.*;

ComponentA a = get(ComponentA.class);
Lazy<ComponentA> lazy_a = inject(ComponentA.class);