gpt4 book ai didi

java - 如何在未启动框架的其他类中获取 BundleContext?

转载 作者:行者123 更新时间:2023-12-01 14:12:29 59 4
gpt4 key购买 nike

我最近开始使用 OSGi 框架。我正在尝试从 Java 主应用程序启动 OSGi 框架。我正在关注这个tutorial将 OSGI 容器嵌入到我的项目中。

下面是我的 Java 主应用程序,我用它来启动 OSGi 容器。在下面的类(class)中,我能够得到 BundleContext使用framework对象,然后我可以使用这个 BundleContext安装实际的OSGi bundles .

public class OSGiBundleTest1 {

public static Framework framework = null;

public static void main(String[] args) throws BundleException {

FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Map<String, String> config = new HashMap<String, String>();

framework = frameworkFactory.newFramework(config);
framework.start();

callMethod();
callMethodOfAnotherClass();
}

private static void callMethodOfAnotherClass() {
OSGiBundleTest2 ss = new OSGiBundleTest2();
ss.someMethod();

}

private static void callMethod() throws BundleException {

BundleContext context = framework.getBundleContext();

System.out.println(context);
}
}

现在这是我在同一个基于 Maven 的项目中的第二堂课。我也需要在这里使用 BundleContext。所以我想我可以使用FrameworkUtil.getBundle(OSGiBundleTest2.class).getBundleContext()获取 BundleContext 但它在这里不起作用,我在那里得到 NPE。这意味着,这个类不是由 OSGi 类加载器加载的。那么现在在下面的类中使用 BundleContext 的最佳方法是什么。

public class OSGiBundleTest2 {

public OSGiBundleTest2() {

}


public static void callMethodOfAnotherClass() {

System.out.println(FrameworkUtil.getBundle(OSGiBundleTest2.class));

BundleContext bundleContext = FrameworkUtil.getBundle(OSGiBundleTest2.class).getBundleContext();
}

}

callMethodOfAnotherClass将从 OSGiBundleTest1 类调用。我不想通过framework对象到 OSGiBundleTest2 类的构造函数或某种使用框架对象的方法,然后从那里获取 BundleContext...还有其他方法可以做到这一点吗?

有什么方法可以确保所有类仅由 OSGI 类加载器加载吗?

最佳答案

确保类被 OSGi 类加载器加载的方法是将它们放入 bundle 中,并实际使用 OSGi 来加载它们。

关于java - 如何在未启动框架的其他类中获取 BundleContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18390585/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com