DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Daniel has posted 1 posts at DZone. View Full User Profile

Get OSGi Service from ServletContext

10.19.2012
| 5638 views |
  • submit to reddit
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()));
 }

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...