OSGi – Accessing Bundle/Service information from BundleContext

Here are few code snippets compiled in a java program, which would help you fetch bundle and service information from BundleContext. The snippets cover:

  • Fetching bundle information
  • Fetching ServiceReference from bundle
  • Fetching Service from bundleContext
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import blog.techrevel.service.BundleInfo;

@Component(immediate = true)
public class BundleInfoImpl implements BundleInfo {
   private static final Logger LOG = LoggerFactory.getLogger(BundleInfoImpl.class);
   private static BundleContext bundleContext;

   public void getBundleInfo(BundleContext bundleContext) {
       //Fetching bundles
       Bundle[] bundles = bundleContext.getBundles();

       for (Bundle bundle : bundles) {
           //Bundle details
           LOG.info("State: " + bundle.getState());
           LOG.info("Symbolic name: " + bundle.getSymbolicName());
           LOG.info("Version:" + bundle.getHeaders().get(Constants.BUNDLE_VERSION).toString());
           LOG.info("Imported Packages:" + bundle.getHeaders().get(Constants.IMPORT_PACKAGE));


   // Fetching ServiceReferernces exposed by the bundle
   public static void extractServicesInfo(Bundle bundle) {
       ServiceReference[] registeredServices = bundle.getRegisteredServices();
       if (registeredServices != null) {
           for (ServiceReference registeredService : bundle.getRegisteredServices()) {
               // Fetching any property of the Service
               LOG.info("service.pid: " + registeredService.getProperty("service.pid"));

               // Fetch Service from ServiceReference
               LOG.info("Service: " + bundleContext.getService(registeredService));

   protected void activate(ComponentContext cc) {
       bundleContext = cc.getBundleContext();

More API details can be retrived from:



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s