Over a million developers have joined DZone.

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()));
 }
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}