Over a million developers have joined DZone.

Get OSGi Service from ServletContext

DZone's Guide to

Get OSGi Service from ServletContext

· ·
Free Resource

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.

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()));

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}