javamonkey79 javamonkey79 - 11 months ago 44
Java Question

Programatically Start OSGi (Equinox)?

I'd like to be able to easily start an OSGi framework (preferably Equinox) and load up any bundles listed in my pom from a java main.

Is this possible? If so, how?

It seems like the pax tools would do this, but I can't seem to find any documentation indicating such. I know I can start up Equinox like so:

BundleContext context = EclipseStarter.startup( ( new String[] { "-console" } ), null );

But I'd like to do more - like I said: load more bundles in, maybe start some services, etc.

Answer Source

Any OSGi framework (R4.1 or later) can be started programmatically using the FrameworkFactory API:

ServiceLoader<FrameworkFactory> ffs = ServiceLoader.load(FrameworkFactory.class);
FrameworkFactory ff = ffs.iterator().next();
Map<String,Object> config = new HashMap<String,Object>();
// add some params to config ...
Framework fwk = ff.newFramework(config);

The OSGi framework is now running. Since Framework extends Bundle you can call getBundleContext and call all of the normal API methods to manipulate bundles, register services, etc. For example

BundleContext bc = fwk.getBundleContext();
bc.registerService(MyService.class.getName(), new MyServiceImpl(), null);
// ...

Finally you should simply wait for the framework to shutdown:


To reiterate, this approach works for any OSGi framework including Equinox and Felix just by putting the framework JAR on the classpath.