Accessing the bundle context¶
Despite iPOJO hides most of the OSGi mechanisms, you often need to access the Bundle Context
. This page explains how you can access to the bundle context from your component code.
Bundle Context¶
The BundleContext
is an object provided by the OSGi Framework to access services as well as resources contained in bundles. Using the bundle context is often required in the later case, i.e. loading files contained in the bundle.
The API of the bundle context is available here.
Retrieving the Bundle Context as constructor parameter¶
The first way to retrieve the bundle context is as a constructor parameter:
public MyComponent(BundleContext context) { // context is the bundle context }
With such way, the bundle context of the bundle declaring the component is injected. Notice that such injection can be mixed with other constructor injection such as @Requires
for service dependencies and @Property
to configuration property.
Using @Context
(version 1.11.2+)¶
The second way to retrieve the Bundle Context
uses a bundle context handler responsible for injecting the bundle context. This handler let you inject the bundle context in a field, in a setter method or as constructor parameter:
@Component public MyComponent { /** * Field injection. */ @Context private BundleContext context; /** * Constructor injection, equivalent to the the previous approach. */ public MyComponent(@Context BundleContext context) { // ... } /** * Method injection. */ @Context public void setBundleContext(BundleContext context) { // ... } }
The @Context
annotation takes an optional parameter indicating which Bundle Context
has to be injected. By default it injects the component
bundle context, meaning the bundle context of the bundle declaring the component. But, you can asks iPOJO to injects the instance
bundle context, i.e. the bundle context of the bundle declaring the instance:
@Component public MyComponent { /** * Injects the instance bundle context */ @Context(Context.Source.INSTANCE) private BundleContext context; }