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?
You can use FrameworkUtil. getBundle(ClassFromBundle). getBundleContext() . See FrameworkUtil JavaDoc.
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.
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.
You can use FrameworkUtil.getBundle(ClassFromBundle).getBundleContext()
.
See FrameworkUtil JavaDoc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With