2009-02-18 110 views
10

我剛剛開始使用Eclipse RCP應用程序,它基本上只是提供的「hello world」示例之一。如何獲取Eclipse RCP應用程序的OSGi BundleContext?

當應用程序啓動時,我想查看我的命令行參數並根據它們啓動一些服務。我可以在IApplication.start得到命令行參數:

public Object start(IApplicationContext context) { 
    String[] argv = (String[]) 
     context.getArguments().get(IApplicationContext.APPLICATION_ARGS))); 
} 

但我怎麼得到BundleContext的,這樣我可以註冊服務?它似乎不在IApplicationContext中。

回答

12

整蠱內部方式:

InternalPlatform.getDefault().getBundleContext() 

能做到這一點。

您將在this class

public class ExportClassDigestApplication implements IApplication { 

    public Object start(IApplicationContext context) throws Exception { 
     context.applicationRunning(); 

     List<ExtensionBean> extensionBeans = ImpCoreUtil.loadExtensionBeans(&quot;com.xab.core.containerlaunchers&quot;); 
     for (ExtensionBean bean : extensionBeans) { 
      ILauncher launcher = (ILauncher) bean.getInstance(); 
      launcher.start(); 
     } 
     ClassFilter classFilter = new ClassFilter() { 
      public boolean isClassAccepted(Class clz) { 
       return true; 
      } 
     }; 

     PrintWriter writer = new PrintWriter(new File("C:/classes.csv")); 

     Bundle[] bundles = InternalPlatform.getDefault().getBundleContext().getBundles(); 

Proper way找到一個例子:

每個plug-in訪問自己的包上下文。

只要確保您的插件類覆蓋了start(BundleContext)方法。然後,您可以將其保存到插件中的類別中,以便輕鬆訪問

請注意,提供給插件的包上下文是特定於此插件的,並且不應與其他插件共享。

+0

但是`start`方法本身需要一個bundle上下文:你會在哪裏提供你的`BundleActivator`?我可以從`FrameworkUtil`中取出它,但是(在我的情況下)是`null`所以...否則你在MANIFEST中聲明你的激活器,所以我得到一個bundle context ..但它是如何給它的? :) – Campa 2015-04-02 08:35:38

+0

@Campa不知道:那是6年以前,我無法再訪問這種項目。你可以通過一個鏈接回到這個問題。 – VonC 2015-04-02 08:49:18

14

剛剛遇到這樣做的網絡搜索,並認爲我會推廣新的標準OSGi R4.2方式(由Equinox隨Eclipse 3.5提供)。如果你沒有激活器,也不想創建一個緩存bundle上下文,你可以使用FrameworkUtil.getBundle。修改前面的例子:

import org.osgi.framework.FrameworkUtil; 

public class ExportClassDigestApplication implements IApplication { 
    public Object start(IApplicationContext context) throws Exception { 
     context.applicationRunning(); 
     BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) 
                .getBundleContext(); 
    } 
} 
相關問題