Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best technique for getting the OSGi bundle context?

Tags:

java

osgi

Each bundle in my OSGi project has its own BundleActivator, which I think is normal. This gets passed the current BundleContext, which is useful to have around for getting service references and whatnot.

However, from classes in my bundle, how can I get the BundleContext? Assigning it to a public static field in the BundleActivator sucks and passing it around as an argument also sucks. Is there a more intelligent way?

like image 365
xconspirisist Avatar asked Jun 29 '11 21:06

xconspirisist


People also ask

How do I get bundle context?

You can use FrameworkUtil. getBundle(ClassFromBundle). getBundleContext() . See FrameworkUtil JavaDoc.

What is bundle context in OSGi?

A BundleContext object is generally for the private use of its associated bundle and is not meant to be shared with other bundles in the OSGi environment. The Bundle object associated with a BundleContext object is called the context bundle.

What is the use of OSGi bundle?

OSGi facilitates creating and managing modular Java components (called bundles) that can be deployed in a container. As a developer, you use the OSGi specification and tools to create one or more bundles. OSGi defines the lifecycle for these bundles. It also hosts them and supports their interactions in a container.


2 Answers

You can use FrameworkUtil.getBundle(ClassFromBundle).getBundleContext().

See FrameworkUtil JavaDoc.

like image 54
Ivan Dubrov Avatar answered Sep 19 '22 13:09

Ivan Dubrov


A good practice when developing OSGi bundles in my opinion is to try to write the OSGi related code as centralized as possible. This way, if you want to use your code in a non-OSGi environment, the migration effort is minimum.

Therefore, using static references or FrameworkUtil all over the place is not a good idea imho. Neither is using plain OSGi. Try to look at iPOJO or Declarative Services.

like image 26
RaduK Avatar answered Sep 21 '22 13:09

RaduK