如何获取Eclipse RCP应用程序的OSGi BundleContext?

我刚刚开始使用Eclipse RCP应用程序,它基本上只是提供的“hello world”示例之一。

当应用程序启动时,我想查看我的命令行参数并根据它们启动一些服务。 我可以在IApplication.start中获取命令行参数:

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

但是如何获得BundleContext,以便我可以注册服务? 它似乎不在IApplicationContext中。

棘手的内部方式:

 InternalPlatform.getDefault().getBundleContext() 

能做到这。

您将在本课程中找到一个示例

 public class ExportClassDigestApplication implements IApplication { public Object start(IApplicationContext context) throws Exception { context.applicationRunning(); List extensionBeans = ImpCoreUtil.loadExtensionBeans("com.xab.core.containerlaunchers"); 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(); 

正确的方法 :

每个插件都可以访问自己的bundle上下文。

只需确保您的插件类重写start(BundleContext)方法。 然后,您可以将其保存到插件中的地方类,可以轻松访问

请注意,提供给插件的bundle上下文是特定于它的,并且永远不应与其他插件共享。

刚刚进行了一次网络搜索,我认为我将推广新的标准OSGi R4.2方式(由Eclipse 3.5附带的Equinox提供)。 如果您没有激活器,并且不想仅仅为了缓存捆绑上下文而创建激活器,则可以使用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(); } }