How do I get the OSGi BundleContext for an Eclipse

2019-03-18 15:32发布

I have just gotten started with an Eclipse RCP application, it is basically just one of the provided "hello world" samples.

When the application boots up, I would like to look at my command-line parameters and start some services according to them. I can get the command-line parameters in IApplication.start:

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

But how do I get the BundleContext, so that I can register services? It does not seem to be in the IApplicationContext.

2条回答
Viruses.
2楼-- · 2019-03-18 15:45

Tricky internal way:

InternalPlatform.getDefault().getBundleContext()

could do it.

You will find an example in 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:

Every plug-in has access to its own bundle context.

Just make sure your plug-in class overrides the start(BundleContext) method. You can then save it to a place classes in your plug-in can easily access

Note the bundle context provided to a plug-in is specific to it and should never be shared with other plug-ins.

查看更多
别忘想泡老子
3楼-- · 2019-03-18 16:07

Just came across this doing a web search, and thought I'd promote the new standard OSGi R4.2 way (as provided by Equinox shipped with Eclipse 3.5). If you don't have an activator, and don't want to create one just to cache the bundle context, you can use FrameworkUtil.getBundle. Modifying the previous example:

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();
    }
}
查看更多
登录 后发表回答