In the OSGi environment, bundles are built around a set of cooperating services that are available from a shared service registry. The service interface defines the OSGi service, which is implemented as a service object.
Services decouple the provider from the service user. The only code a service provider and a service user share is the service definition. You can use Java interfaces to define services. Any class that implements this interface can provide the service.
Bundles that use services that are not provided by the bundle can notify the framework by including an Import-Service header in the bundle manifest. However, this is not required. When code within a bundle requests a provider of the service from the framework, the bundle imports the service at runtime.
A bundle that provides services can also include an Export-Service header in its manifest. When code within a bundle makes a provider available to the framework, the bundle exports the service at runtime.
Registering and unregistering a service with the OSGi Framework: XPD621
The framework passes a BundleContext
object to your bundle when it invokes your BundleActivator
's start method. Your bundle can use the BundleContext
object to interact with the framework by calling the methods of the BundleContext
object. One method that your bundle can call is registerService
, which uses a service object and an interface name to register a service with the framework's service registry.
Getting and ungetting services from the OSGi Framework: XPD621
Bundles register and unregister services. Bundles that depend on services must account for the possibility that the requested service might not be available. The service can register or unregister with the framework at any time.
Parent topic: Working with OSGi bundles: XPD621