2013-08-22 28 views
0

我最近開始使用OSGi框架。我正嘗試從Java主應用程序啓動OSGi框架。我正在關注這個tutorial以將OSGI容器嵌入到我的項目中。如何在其他未啓動框架的類中獲得BundleContext?

下面是我用來啓動OSGi容器的Java主應用程序。在下面的課程中,我可以使用framework對象獲得BundleContext,然後我可以使用此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 classloader加載?

+0

「任何方式來確保所有的類只能被OSGI classloader加載」嗯,是的,把它們放在OSGi包中。對不起,但這不明顯? –

+1

TechGeeky,請閱讀'OSGi in Action'或遵循網絡上的許多教程。我不認爲Stackoverflow適用於您在遵循一些初學者教程時非常明顯的問題嗎?另外,從bndtools開始,而不是低級啓動API,以便您可以在嘗試修改它們之前先了解這些概念。 –

回答

1

確保類通過OSGi類加載器加載的方法是將它們放入捆綁包中並實際使用OSGi加載它們。

相關問題