Platinum Partner

Get OSGi Service from ServletContext

Both OSGi and Web application have their own type of context. In OSGi the context is called BundleContext that allows under among other things to register service objects with the framework service registry. In a web application environment it is named ServletContext.

For getting the BundleContext within a servlet you have to inject first the ServletContext. With the given snippet you are able to get any registered OSGi service.

more...
public static  T getService(ServletContext servletContext, Class serviceInterface) {
  BundleContext bundleContext = (BundleContext) servletContext.getAttribute("osgi-bundlecontext");
  if (bundleContext == null) {
   throw new IllegalStateException("osgi-bundlecontext not registered");
  }
  return getService(bundleContext, serviceInterface);
 }

public static  T getService(BundleContext bundleContext, Class serviceInterface) {
  return (T) bundleContext.getService(bundleContext.getServiceReference(serviceInterface.getName()));
 }
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}