0

我最近开始使用 OSGi 框架。我正在尝试从 Java 主应用程序启动 OSGi 框架。我正在按照本教程将 OSGI 容器嵌入到我的项目中。

下面是我用来启动 OSGi 容器的 Java 主应用程序。在下面的课程中,我可以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 类加载器加载?

4

1 回答 1

1

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

于 2013-08-26T01:15:10.703 回答