Kotlin 与 OSGi

如果想要在项目中启用 Kotlin OSGi 支持,需要引入 kotlin-osgi-bundle 而不是常规的 Kotlin 库。 建议删除 kotlin-runtime、 kotlin-stdlib 与 kotlin-reflect 依赖, 因为 kotlin-osgi-bundle 已经包含了所有这些。当引入外部 Kotlin 库时也应该注意。 大多数常规 Kotlin 依赖不是 OSGi-就绪的,所以不应该使用且应从项目中删除。

Maven

将 Kotlin OSGi 包引入到 Maven 项目中:

1. <dependencies>
2. <dependency>
3. <groupId>org.jetbrains.kotlin</groupId>
4. <artifactId>kotlin-osgi-bundle</artifactId>
5. <version>${kotlin.version}</version>
6. </dependency>
7. </dependencies>

从外部库中排除标准库(注意“星排除”只在 Maven 3 中有效):

1. <dependency>
2. <groupId>some.group.id</groupId>
3. <artifactId>some.library</artifactId>
4. <version>some.library.version</version>

6. <exclusions>
7. <exclusion>
8. <groupId>org.jetbrains.kotlin</groupId>
9. <artifactId>*</artifactId>
10. </exclusion>
11. </exclusions>
12. </dependency>

Gradle

将 kotlin-osgi-bundle 引入到 Gradle 项目中:

【Kotlin】

1. dependencies {
2. implementation(kotlin("osgi-bundle"))
3. }

【Groovy】

1. dependencies {
2. implementation "org.jetbrains.kotlin:kotlin-osgi-bundle:1.9.10"
3. }

要排除作为传递依赖的默认 Kotlin 库,你可以使用以下方法:

【Kotlin】

1. dependencies {
2. implementation("some.group.id:some.library:someversion") {
3. exclude(group = "org.jetbrains.kotlin")
4. }
5. }

【Groovy】

1. dependencies {
2. implementation('some.group.id:some.library:someversion') {
3. exclude group: 'org.jetbrains.kotlin'
4. }
5. }

FAQ

为什么不只是添加必需的清单选项到所有 Kotlin 库

尽管它是提供 OSGi 支持的最好的方式,遗憾的是现在做不到,是因为不能轻易消除的所谓的 “包拆分”问题并且这么大的变化不可能现在规划。有 Require-Bundle 功能,但它也不是最好的选择,不推荐使用。 所以决定为 OSGi 做一个单独的构件。