How to get a service reference outside the OSGi context

Solution Verified - Updated -

Environment

  • Red Hat JBoss Fuse 6.1.0

Issue

How can I get the reference to the OSGi service from the objects not created using Blueprint?

Resolution

You can use OSGi FrameworkUtil [1] to get the reference to the bundle context from any object. The snippet below demonstrates how to get reference to the BundleContext using mentioned utility:

  BundleContext bundleContext = FrameworkUtil.getBundle(JpaPublisher.class).getBundleContext();

Having bundle context, you can retrieve the reference to the any service from it. The service can be resolved as follows:

  ServiceReference ref = bundleContext.getServiceReference(MyService.class.getName());
  MyService service = (MyService) bundleContext.getService(ref);

[1] https://osgi.org/javadoc/r4v43/core/org/osgi/framework/FrameworkUtil.html

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.

Close

Welcome! Check out the Getting Started with Red Hat page for quick tours and guides for common tasks.