如何在 OSGI 包中嵌入外部 jars 依赖项?

Uda*_*gra 5 osgi maven apache-felix

我正在尝试将我的项目转换为 OSGI 应用程序。我几乎没有怀疑。假设我的应用程序中的 ModuleA 依赖于外部 jarA 和 jarB。现在为了让 ModeuleA 运行,我使用 maven-bundle-plugin 的 embed-dependency 属性嵌入了两个 jar。现在假设我有另一个模块 ModuleB,它也依赖于 jarA。所以这个模块也嵌入了jarA。我的项目最终将 jarA 嵌入了 2 次,这将不必要地膨胀项目的大小。

有什么方法可以告诉 OSGI 只加载一次 jarA 并将其提供给两个模块。

如果将这些 jars 转换为 OSGI 包是唯一的解决方案,我还有几个问题:

  1. 将 jar 转换为包的最简单方法是什么。BND 工具看起来是一个不错的解决方案,但我找不到有关它的正确文档。

  2. jarA 也会有一些依赖的 jars。那么我是否需要将所有依赖的 jar 也转换为包。我的项目有 100 多个罐子。我怎样才能自动化这个过程。

提前致谢 :)

Jen*_*ens 4

实际上有一些解决方案,都与您现在正在做的有点不同:

  1. 构建一个“第三方依赖项”包,它将嵌入您的项目具有的所有非 OSGi 依赖项。
  2. 将每个非 OSGi 依赖项转换为 OSGi 包。

选项 1 更容易处理,所以我认为大多数项目都会这样做。我个人更喜欢选项 2。我们有一个 Maven“pom.xml”模板,用于转换这些依赖项。

“pom.xml”看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <properties>
        <library.groupId></library.groupId>
        <library.artifactId></library.artifactId>
        <library.version></library.version>
    </properties>

    <artifactId></artifactId>
    <packaging>bundle</packaging>

    <name></name>
    <description>${library.groupId}:${library.artifactId}:${library.version}</description>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Import-Package>*;resolution:=optional</Import-Package>
                        <Export-Package>*</Export-Package>
                        <Embed-Dependency>*;scope=compile|runtime;inline=true</Embed-Dependency>
                        <Embed-Transitive>true</Embed-Transitive>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>${library.groupId}</groupId>
            <artifactId>${library.artifactId}</artifactId>
            <version>${library.version}</version>
        </dependency>
    </dependencies>

</project>
Run Code Online (Sandbox Code Playgroud)

这会:

  1. 添加非 OSGi 库作为依赖项
  2. 告诉maven-bundle-plugin嵌入此依赖项(传递)
  3. 告诉maven-bundle-plugin导出所有依赖包

我将一些您必须设置的内容留空library.groupId,例如library.artifactIdlibrary.version。我们需要调整maven-bundle-plugin. 但这是我们的出发点。例如,您不想导出所有包等。

如果您确实有 100 多个依赖项需要转换,您可能最好使用此模板,只需将所有 100 个依赖项添加为依赖项,然后构建一个包含所有这些依赖项的大包。

您可以在此处找到相关文档maven-bundle-plugin

https://felix.apache.org/documentation/subprojects/apache-felix-maven-bundle-plugin-bnd.html

在这一点上,我还想提一下,您可能需要考虑一个新的捆绑插件:bnd-maven-plugin

请参阅:https ://github.com/bndtools/bnd/tree/master/maven/bnd-maven-plugin