簡體   English   中英

嵌入式OSGi:訪問動態加載的包組件

[英]Embedded OSGi: accessing dynamically loaded bundle components

在將OSGi嵌入到應用程序/庫中,在運行時加載捆綁軟件然后在主機應用程序/庫中使用該捆綁軟件時,我有些迷惑。

這是從我的主機加載捆綁軟件的代碼:

// framework is the embedded OSGi framework
Bundle b = framework.getBundleContext().installBundle( "file:/project_dir/bundle/MyBundle.jar" );
b.start();

捆綁包含非常簡單的內容:

public class Activator implements BundleActivator
{
  @Override
  public void start( BundleContext context )
  {
  }

  @Override
  public void stop( BundleContext context )
  {
  }

  public String shout()
  {
    return "let it all out";
  }
}

如何從主機應用程序訪問shout()方法?

簡而言之:

  • 將對象注冊為OSGi服務
  • 在啟動嵌入式OSGi容器的應用程序/庫中獲取OSGi服務

更詳細的解決方案:

  • 在包含shout()函數的單獨jar中定義一個接口
  • 將jar文件放在應用程序/庫的類路徑中
  • 在包的Activator類中實現接口
  • 根據接口將Activator類的實例注冊為OSGi服務
  • 在應用程序/庫中,基於接口獲取OSGi服務

或者,如果您在應用程序/庫中沒有該接口,則仍然可以獲取OSGi服務並使用反射調用該函數。

以下是有關在先前答案之后使用的代碼的一些詳細信息:

  • 包含您的方法的接口。

     public interface MyInterface { String shout(); } 

    您可能會注意到,為庫提供兩個捆綁是一個好方法:一個捆綁用於接口,另一個捆綁用於實現。 當實現包再次出現時,它將防止出現“刷新包”問題。

  • 上一個接口的實現:

     public class MyImpl implements MyInterface { public String shout() { return "let it all out"; } } 

    該實現的包不需要通過捆綁包導出。 服務使用者不會直接使用MyImpl類。

  • 激活器的新代碼:

     public class Activator implements BundleActivator { private ServiceRegistration serviceRegistration; @Override public void start( BundleContext context ) { this.serviceRegistration = context.registerService( MyInterface.class, new MyImpl(), new HashMap<String,String>()); } @Override public void stop( BundleContext context ) { if (serviceRegistration!=null) { serviceRegistration.unregister(); } } } 

    包含激活器和實現的捆綁軟件需要將接口的包導入其文件MANIFEST.MF 激活程序的包或實現都不需要在此文件中導出。 它們必須保持在捆綁包內部。

  • 使用另一個捆綁軟件中的服務的類

     public void callService() { ServiceReference<MyInterface> reference = bundleContext.getServiceReference(MyInterface.class); MyInterface foo = bundleContext.getService(reference); try { //use service String msg = service.shout(); } finally { bundleContext.ungetService( reference ); } } 

    您會注意到,使用者僅需要導入接口的包(而不是實現的包)。 此外,您需要小心處理OSGi的動態。 該服務可能在兩次通話之間就消失了!

希望對您有幫助,蒂埃里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM