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.



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:



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.