Dienstag, 25. Oktober 2011

OSGi - How to get the Bundle Context in a Java Object Instance

In most cases I use DS components, when I need the bundle context instance, the DS Framework injects me the bundle context in the activation method of my component. In most components I don’t like to have a dependency on OSGi APIs in my DS components, but thats another topic.

But sometimes I need an OSGi service or the BundleContext also in non OSGi / DS controlled class. E.g. when I like to write a JAX-WS web service class. There are many ways to get the Bundle Context into this type of Objects. One is to get the Bundle Context from the ClassLoader (which should implements the BundleReference interface). Here a short demo code snippet how to get the bundle API and also the bundle context of a class.

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
public class MyDemoClass
{
public PackageAdmin getService()
{
// Howto get a bundle context
BundleContext ctx =
BundleReference.class.cast(MyDemoClass.class.getClassLoader())
.getBundle()
.getBundleContext();
// Only demo code ugly service handling
ServiceReference serviceReference = ctx.getServiceReference(PackageAdmin.class.getName());
return PackageAdmin.class.cast(ctx.getService(serviceReference));
}
}


Comment: "However, this requires the code to have the permission to access the class loader." OSGi Core Specification see section 3.8.9.

Better implementation (thanks at Holger for the hint) is by using the OSGi FrameworkUtil class. See the second code snippet:

import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
public class MyDemoClass
{
public PackageAdmin getService()
{
// get bundle instance via the OSGi Framework Util class
BundleContext ctx = FrameworkUtil.getBundle(MyDemoClass.class).getBundleContext();
ServiceReference serviceReference = ctx.getServiceReference(PackageAdmin.class.getName());
return PackageAdmin.class.cast(ctx.getService(serviceReference));
}
}


Another solution could be a holder class with a static field, which holds the actual bundle context instance. This also works when the code does not have the permission to access the class loader.